C++ | C++ 类 & 对象 | 类的静态成员
C++类的静态成员
可以使用 static 关键字来把类成员定义为静态的。
当声明类的成员为静态时,这意味着无论创建多少个类的对象,静态成员都只有一个副本
。
静态成员在类的所有对象中是共享的。如果不存在其他的初始化语句,在创建第一个对象时,所有的静态数据都会被初始化为零。我们不能把静态成员的初始化放置在类的定义中,但是可以在类的外部通过使用范围解析运算符 ::
来重新声明静态变量从而对它进行初始化,如下面的实例所示。
实例1:
/*******************************************************************
* > File Name: classStaticMember.cpp
* > Create Time: 2021年09月 3日 16:44:12
******************************************************************/
#include <iostream>
using namespace std;
class Box{
public:
static int objcount /*= 0 */;//ISO C++ 不允许在类内初始化非常量静态成员
Box(double l=2.0, double w=2.0, double h=2.0){
cout << "calling constructor" << endl;
length = l;
width = w;
height = h;
objcount ++; // 每次创建对象加1
}
double volume(void){
return (length*width*height);
}
protected:
private:
double length;
double width;
double height;
};
// 初始化类Box的静态变量objcount
int Box::objcount = 0;
int main(void)
{
Box box1(2.0, 3.0, 4.0);
Box box2(3.0, 4.0, 5.0);
/* 输出对象的总数 */
cout << "Total objects: " << Box::objcount << endl;
return 0;
}
编译、运行:
PS E:\fly-prj\cplusplus\day5> make
g++ -o classStaticMember classStaticMember.cpp -g -Wall
PS E:\fly-prj\cplusplus\day5> .\classStaticMember.exe
calling constructor
calling constructor
Total objects: 2
静态成员函数
如果把函数成员声明为静态的,就可以把函数与类的任何特定对象独立开来。
静态成员函数即使在类对象不存在的情况下也能被调用,静态函数只要使用类名加范围解析运算符 ::
静态成员函数只能访问静态成员数据、其他静态成员函数和类外部的其他函数。
静态成员函数有一个类范围,他们不能访问类的 this
指针。您可以使用静态成员函数来判断类的某些对象是否已被创建。
静态成员函数与普通成员函数的区别:
- 静态成员函数没有
this
指针,只能访问静态成员(包括静态成员变量和静态成员函数)。 - 普通成员函数有
this
指针,可以访问类中的任意成员;而静态成员函数没有this
指针。
实例2:
/*******************************************************************
* > File Name: classStaticFunc.cpp
* > Create Time: 2021年09月 3日 17:20:57
******************************************************************/
#include <iostream>
using namespace std;
class Box{
public:
static int objcount;
/* 定义构造函数 */
Box(double l, double w, double h){
cout << "calling constructor" << endl;
length = l;
width = w;
height = h;
objcount ++; /* 每次创建对象加1 */
}
double volume(void){
return (length*width*height);
}
static int getcount(void){
return objcount;
}
protected:
private:
double length; /* 长度 */
double width; /* 宽度 */
double height; /* 高度 */
};
int Box::objcount = 0; /* 初始化类 Box 的静态成员 */
int main(void)
{
cout << "Init stage count: " << Box::getcount() << endl;
Box box1(2.0, 3.0, 4.0); /* 声明对象box1 */
Box box2(3.0, 4.0, 5.0); /* 声明对象box2 */
cout << "final stage count: " << Box::getcount() << endl;
return 0;
}
编译、运行:
PS E:\fly-prj\cplusplus\day5> make
g++ -o classStaticFunc classStaticFunc.cpp -g -Wall
PS E:\fly-prj\cplusplus\day5> .\classStaticFunc.exe
Init stage count: 0
calling constructor
calling constructor
final stage count: 2