相关内容:
- 父类的
static
变量和函数在派生类中依然可用,但是受访问性控制(比如,父类的private
域中的就不可访问),而且对static
变量来说,派生类和父类中的static
变量是共用空间的,这点在利用static
变量进行引用计数的时候要特别注意。 static
函数没有“虚函数”一说。- 静态变量并不是说其就不能改变值,不能改变值的量叫常量(即
const
), 其拥有的值是可变的 ,而且它会保持最新的值。说其静态,是因为它不会随着函数的调用和退出而发生变化。即上次调用函数的时候,如果我们给静态变量赋予某个值的话,下次函数调用时,这个值保持不变。 - 静态变量 类型说明符是
static
。 - 静态变量属于静态存储方式,其存储空间为内存中的静态数据区(在 静态存储区内分配存储单元),该区域中的数据在整个程序的运行期间一直占用这些存储空间(在程序整个运行期间都不释放),也可以认为是其内存地址不变,直 到整个程序运行结束(相反,而
auto
自动变量,即动态局部变量,属于动态存储类别,占动态存储空间,函数调用结束后即释放)。静态变量虽在程序的整个执 行过程中始终存在,但是在它作用域之外不能使用。 - 属于静态存储方式的量不一定就是静态变量。 例如:外部变量虽属于静态存储方式,但不一定是静态变量,必须由 static加以定义后才能成为静态外部变量,或称静态全局变量。
- 所有的全局变量都是静态变量,而局部变量只有定义时加上类型修饰符
static
,才为局部静态变量。静态变量可以在任何可以申请的地方申请,一旦申请成功后,它将不再接受其他的同样申请。 - 在类的继承中,基类的
static
成员变量或成员函数在派生类中都是可用的,但有access permission
控制(如,基类的private
域中static
成员不可以访问),再者需要注意的一点,static
成员变量在基类和派生类中是共用空间的。代码相关内容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using namespace std;
class A
{
public:
static std::size_t object_count()
{
return 100;
}
protected:
static const std::size_t obj_count = 99;
};
class B : public A
{
public:
void f(const B &b,B *b2)
{
// static成员变量
cout << A::obj_count << endl; // 通过 基类名::成员名 来访问static成员;
cout << B::obj_count << endl; // 通过 子类名::成员名 来访问static成员;
cout << b.obj_count << endl; // 通过 对象.成员名 来访问static成员;
cout << b2->obj_count << endl; // 通过 指针->成员名 来访问static成员;
cout << obj_count << endl; //直接访问;
// static成员函数(5种方法)
cout << A::object_count() << endl;
cout << B::object_count() << endl;
cout << b.object_count() << endl;
cout << b2->object_count() << endl;
cout << object_count() << endl;
}
};
class C : public B
{
};
int main()
{
B b;
b.f(b, &b);
return 0;
}代码执行结果:
参考链接:
c++中 static 变量和函数能否被子类继承
C++ 类继承中static成员的辨析