静态成员使用遵循以下几点:
- 静态成员变量不能通过参数列表来初始化,只能在类外初始化(int ClsTest::total = 0;),如果不初始化则为编译器默认值;
- 静态成员常量可以在类内定义时直接初始化,也可以像静态成员变量一样类内声明,类外定义;
- 静态成员是属于类而不是属于对象,不占用对象的空间,但对象可以引用它,不需要使用特殊的格式,是所有对象共有,一旦改变,各对象都跟着改变;
- static成员依然保持public,private,protected访问准则;
#include <iostream>
using namespace std;
class ClsTest
{
public:
static int total;
private:
static const int rate = 100;
};
int ClsTest::total = 0;
int main()
{
ClsTest t1, t2;
t1.total = 100;
cout << "Total 1: " << t2.total << endl;
cout << "Total 2: " << ClsTest::total << endl;
return 0;
}
- 普通成员函数可以引用所有的成员(不管是否为静态),而静态成员函数只能使用静态成员而不能访问其他非静态成员;
#include <iostream>
using namespace std;
class ClsTest
{
public:
static void s_func(){
s_test();
}
void func(){
s_test();
test();
}
private:
static void s_test(){
cout << "s_test" << endl;
}
void test(){
cout << "test" << endl;
}
};
int main()
{
ClsTest t1;
t1.s_func();
t1.func();
return 0;
}
- 子类继承之后依然保持着静态变量,不需要重复初始化。
#include <iostream>
using namespace std;
class ClsTest
{
public:
static int total;
};
int ClsTest::total = 0;
class ClsTest2 : public ClsTest
{
};
int main()
{
ClsTest t1;
t1.total = 100;
cout << "Total 1: " << ClsTest::total << endl;
ClsTest2 t2;
cout << "Total 2: " << t2.total << endl;
cout << "Total 3: " << ClsTest2::total << endl;
return 0;
}