Qt 静态成员函数的调用非静态成员变量,非静态成员函数

4 篇文章 0 订阅
  1. 在多人开发的项目中,一些通用的工具类接口可以用静态成员函数。方便调用,并且不容易调用错误。
  2. 静态成员函数不传递this指针(不能->),不识别对象个体,所以经常用于对静态数据成员进行操作。不能操作非静态成员变量。
  3. 静态成员函数如果必须访问非静态成员变量,必须通过对象来引用。
#ifndef MYSTAIC_H
#define MYSTAIC_H

#include <QObject>
#include <QDebug>
#include <QString>
#include <QMutex>

class MyStaic : public QObject
{
    Q_OBJECT
public:
    explicit MyStaic(QObject *parent = 0);
    ~MyStaic();
    static  void  test();
    static  void  test(MyStaic &myStaic);
    static QMutex*  mutex;
    void  notStaticfun();
private:
    int  tmp ;

};

#endif // MYSTAIC_H
  • MyStaic 作为static测试类,test作为普通的静态函数。
  • 带参数的test函数作为访问非静态成员变量的静态函数
  • mutex为静态成员变量,用于静态成员函数中调用
  • notStaticfun() 函数为普通成员函数,用于静态成员函数调用
#include "mystaic.h"
QMutex*  MyStaic::mutex = new QMutex;

MyStaic::MyStaic(QObject *parent) : QObject(parent)
{
    qDebug() << "This is  构造函数";
    tmp = 10;
}


MyStaic::~MyStaic()
{
    qDebug() << "this is 析构";
}

void MyStaic::test()
{
    qDebug() <<  "OK";
    mutex->lock();
    mutex->unlock();


}

void MyStaic::test(MyStaic &myStaic)
{
    qDebug() << "This is not static Member variables tmp =" << myStaic.tmp ;
    myStaic.notStaticfun();
}

void MyStaic::notStaticfun()
{
    qDebug() <<  "This  is  not  static  fun";
}

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "mystaic.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    MyStaic::test();
    MyStaic*  myNoStatic = new MyStaic(this);
    MyStaic::test(*myNoStatic);
}

MainWindow::~MainWindow()
{
    delete ui;
}

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}


本程序的运行结果为:

OK

This is 构造函数

This is not static Member variables tmp = 10

This is not static fun

this is 析构




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值