1 静态类成员变量
- 无论创建了多少对象,程序都只创建一个静态类变量副本。这对于所有类对象都共享的具有相同值的类私有数据是很方便的。
- 静态类成员变量单独存储,不是对象的组成部分。
- 要在类的实现文件中对其进行初始化,因为如果在头文件中初始化,将头文件包含在不同的文件中时,会在多处出现初始化副本而出现错误。
#ifndef CL_STUDENT_H
#define CL_STUDENT_H
#include <QString>
class cl_student
{
private:
QString m_name;
static QString sta_school;
public:
cl_student(QString name);
~cl_student();
};
#endif
#include <student.h>
QString cl_student::sta_school = "UESTC";
cl_student::cl_student(QString name)
{
m_name = name;
}
cl_student::~cl_student()
{
}
2 静态类成员函数
- 不能通过对象调用静态类成员函数,它也不能使用this指针。
- 不与特定的对象相关联,只能使用静态类数据成员。
- 如果静态类成员函数在public部分被声明,在类外我们可以用类名加作用域解析运算符来调用它。
- 静态类成员函数在类头文件声明时加static,在类实现文件中不用加static。
#ifndef CL_STUDENT_H
#define CL_STUDENT_H
#include <QString>
class cl_student
{
private:
QString m_name;
static QString sta_school;
public:
cl_student(QString name);
~cl_student();
static QString getSchool();
};
#endif
#include <student.h>
QString cl_student::sta_school = "UESTC";
QString cl_student::getSchool()
{
return sta_school;
}
cl_student::cl_student(QString name)
{
m_name = name;
}
cl_student::~cl_student()
{
}
#include<qDebug>
#include <QString>
int main()
{
cl_student mystudent("dwp");
QString school = cl_student::getSchool();
qDebug() << school;
}
3 静态类成员常量
- 定义静态类成员常量相当于在类中定义了常量,可在多个对象间共享只读数据。
- 该常量与其它静态变量存储在一起,不存储在对象中。属于类,不属于某个类对象。
- 对静态类成员常量,类只有一个,被所有构造的类对象共享。
- 在类头文件中定义时就可以初始化。
#ifndef CL_STUDENT_H
#define CL_STUDENT_H
#include <QString>
class cl_student
{
private:
QString m_name;
static QString sta_school;
static const QString country = "CHINA";
public:
cl_student(QString name);
~cl_student();
};
#endif
#include <student.h>
QString cl_student::sta_school = "UESTC";
cl_student::cl_student(QString name)
{
m_name = name;
}
cl_student::~cl_student()
{
}