日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++工作笔记-对全局变量的进一步认识(何时适合用,何时不适合用)

發(fā)布時間:2025/3/15 c/c++ 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++工作笔记-对全局变量的进一步认识(何时适合用,何时不适合用) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

關(guān)于全局變量的好處,和壞處,在此不說了,還沒畢業(yè)的大學生基本上對全局變量都有認識。

在此,我只記錄下今天的感悟!!!

?

首先來看一個程序:

這里面有2個QLineEdit,一個QLineEdit一秒+1,另外一個半秒+1

運行截圖如下:

這個是正常的狀態(tài),源碼如下:

mylineedit.h

#ifndef MYLINEEDIT_H #define MYLINEEDIT_H#include <QLineEdit>class MyLineEdit : public QLineEdit {Q_OBJECT public:MyLineEdit(QWidget *parent = 0);void setStartTime(const int time);protected:void timerEvent(QTimerEvent *event);private:int m_num; };#endif // MYLINEEDIT_H

widget.h

#ifndef WIDGET_H #define WIDGET_H#include <QWidget>namespace Ui { class Widget; }class Widget : public QWidget {Q_OBJECTpublic:explicit Widget(QWidget *parent = 0);~Widget();private:Ui::Widget *ui; };#endif // WIDGET_H

main.cpp

#include "widget.h" #include <QApplication>int main(int argc, char *argv[]) {QApplication a(argc, argv);Widget w;w.show();return a.exec(); }

mlineedit.cpp

#include "mylineedit.h" #include <QTimerEvent> #include <QDebug>MyLineEdit::MyLineEdit(QWidget *parent) : QLineEdit(parent) {m_num=0; }void MyLineEdit::setStartTime(const int time) {startTimer(time); }void MyLineEdit::timerEvent(QTimerEvent *event) {Q_UNUSED(event)m_num++;this->setText(QString::number(m_num)); }

widget.cpp

#include "widget.h" #include "ui_widget.h"Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget) {ui->setupUi(this);ui->lineEdit->setStartTime(1000);ui->lineEdit_2->setStartTime(500); }Widget::~Widget() {delete ui; }

然而如果把m_num改成全局變量的就會發(fā)現(xiàn)很搞笑的事情!

運行截圖如下:

改動源碼如下:

mylineedit.h

#ifndef MYLINEEDIT_H #define MYLINEEDIT_H#include <QLineEdit>class MyLineEdit : public QLineEdit {Q_OBJECT public:MyLineEdit(QWidget *parent = 0);void setStartTime(const int time);protected:void timerEvent(QTimerEvent *event);private:};#endif // MYLINEEDIT_H

mylineedit.cpp

#include "mylineedit.h" #include <QTimerEvent> #include <QDebug>int m_num=0;MyLineEdit::MyLineEdit(QWidget *parent) : QLineEdit(parent) { }void MyLineEdit::setStartTime(const int time) {startTimer(time); }void MyLineEdit::timerEvent(QTimerEvent *event) {Q_UNUSED(event)m_num++;this->setText(QString::number(m_num)); }

?

總結(jié):

從這里面可以看到,當某一個類,要有多個實例的實例的時候,除非多線程,搶臨界資源這種情況,其他情況就非常不合適全局變量,而一個類只有一個實例(單例模式)這種情況,就可以使用全局變量,簡化邏輯,當然,這可能對后期的維護有影響。

新人創(chuàng)作打卡挑戰(zhàn)賽發(fā)博客就能抽獎!定制產(chǎn)品紅包拿不停!

總結(jié)

以上是生活随笔為你收集整理的C++工作笔记-对全局变量的进一步认识(何时适合用,何时不适合用)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。