- 在多人开发的项目中,一些通用的工具类接口可以用静态成员函数。方便调用,并且不容易调用错误。
- 静态成员函数不传递this指针(不能->),不识别对象个体,所以经常用于对静态数据成员进行操作。不能操作非静态成员变量。
- 静态成员函数如果必须访问非静态成员变量,必须通过对象来引用。
#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 析构