c++ 类中,用static 修饰的成员称为静态成员。是一个在类域中的全局变量。
1. 静态成员的特点
(1) 仅在类域中可见,在类域外不可见。
(2) 独立于类对象存在,不出现在类对象的内存结构中。在创建任何类对象前,就已经存在。
无论创建多少个类对象,类中都仅有一个静态变量的对象,存储于全局变量区中。
(3) 类的所有对象,包括派生类对象,都共享这一个静态成员。
(4) 静态成员可以是所属的类类型,而普通的成员只能是所属类类型的指针或引用。
(5) 静态成员和mutable成员一样,可以在类的 const 函数中被合法的改变。
2. 静态成员的定义与赋值
只能在类的定义体外进行定义与赋值。在类中的静态成员,其实仅仅是一个声明,即静态变量在此类域中。必须在外部进行定义,如果要访问此静态变量,还需要在外部对其赋值。
(1) 在类定义的内部进行初始化,编译器报错,因为类内部的静态成员仅仅是一个声明,不能对其赋值。
#include <stdlib.h>
#include <iostream>
using namespace std;
class apple
{
public:
apple(int price)
:m_price(price)
{
}
public:
int m_price;
static int m_count = 10;
};
//int apple::m_count = 10;
int main(int argc, char **argv)
{
apple APPLE_1(5);
apple APPLE_2(7);
cout << "---apple::m_count---" << apple::m_count << endl;
cout << "---APPLE_1.m_count---" << APPLE_1.m_count << endl;
cout << "---APPLE_2.m_count---" << APPLE_2.m_count << endl;
}
编译结果如下。编译器禁止在类定义中,对于非 const 的静态成员初始化。
(2) 未定义进行访问
#include <stdlib.h>
#include <iostream>
using namespace std;
class apple
{
public:
apple(int price)
:m_price(price)
{
}
public:
int m_price;
static int m_count;
};
//int apple::m_count = 10;
int main(int argc, char **argv)
{
apple APPLE_1(5);
apple APPLE_2(7);
cout << "---apple::m_count---" << apple::m_count << endl;
cout << "---APPLE_1.m_count---" << APPLE_1.m_count << endl;
cout << "---APPLE_2.m_count---" << APPLE_2.m_count << endl;
}
编译结果如下。可见编译器认为此静态变量并没有进行定义,所以对此静态变量的引用报错了。
3. 静态成员的访问
(1) public,private,protected 控制其可见性。
(2)可通过如下方式访问
类名::静态成员变量
类对象.静态成员变量 (不推荐)
(3)可以被类中的静态和非静态成员函数访问。
静态成员的使用例子,如下
#include <stdlib.h>
#include <iostream>
using namespace std;
class apple
{
public:
apple(int price)
:m_price(price)
{
}
int count()
{
return m_count;
}
static int static_count()
{
return m_count;
}
public:
int m_price;
static int m_count;
};
int apple::m_count = 10;
int main(int argc, char **argv)
{
apple APPLE_1(5);
apple APPLE_2(7);
// 不同的访问静态成员的方式
cout << "---apple::m_count---" << apple::m_count << endl;
cout << "---APPLE_1.m_count---" << APPLE_1.m_count << endl;
cout << "---APPLE_2.m_count---" << APPLE_2.m_count << endl;
// 通过一个对象修改静态成员
APPLE_1.m_count = 13;
cout << endl;
cout << "---apple::m_count---" << apple::m_count << endl;
cout << "---APPLE_1.m_count---" << APPLE_1.m_count << endl;
cout << "---APPLE_2.m_count---" << APPLE_2.m_count << endl;
cout << endl;
// 非静态函数访问静态成员
cout << "---APPLE_1.count()---" << APPLE_1.count() << endl;
// 静态函数访问静态成员
cout << "---APPLE_1.static_count()---" << APPLE_1.static_count() << endl;
}
执行结果如下: