C++中static变量与继承

来源:互联网 发布:c语言玫瑰花效果图 编辑:程序博客网 时间:2024/06/08 15:07

1.   父类的static变量和函数在派生类中依然可用,但是受访问性控制(比如,父类的private域中的就不可访问),而且对static变量来说,派生类和父类中的static变量是共用空间的,这点在利用static变量进行引用计数的时候要特别注意。   
  2.   static函数没有“虚函数”一说。因为static函数实际上是“加上了访问控制的全局函数”,全局函数哪来的什么虚函数?   
  3.   派生类的friend函数可以访问派生类本身的一切变量,包括从父类继承下来的protected域中的变量。但是对父类来说,他并不是friend的。

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include<iostream>  
  2. using namespace std;  
  3. class A  
  4. {  
  5. public:  
  6.     static int num;  
  7. };  
  8. int A::num=100;  
  9.   
  10. class B:public A  
  11. {  
  12. public:  
  13.     int i;  
  14.     B(int m):i(m)  
  15.     {}  
  16. };  
  17.   
  18. //int B::num=200;  
  19. int main()  
  20. {  
  21.     B b(5);  
  22.   
  23.     cout << b.num << endl;  
  24.     b.num = 10;  
  25.     cout << b.num << endl;  
  26.     cout << B::num << endl;  
  27.     cout << A::num << endl ;  
  28.   
  29.     cout << &B::num << endl;  
  30.     cout << &A::num << endl;  
  31.     cout << &b.num << endl;  
  32.   
  33.     return 0;  
  34. }  


测试代码会发现A、B类中的 num 值相等,然后查看地址发现地址也相等。所以父类子类指向是同一个全局数据区的static变量。此外 如果定义 int B::num=200; 会出现编译错误

0 0
原创粉丝点击