C++ //继承同名静态成员处理方式

 1 //继承同名静态成员处理方式
 2 #include <iostream>
 3 #include <string>
 4 using namespace std;
 5 
 6 class Base
 7 {
 8 public:
 9     static int m_A;
10 
11     static void func()
12     {
13         cout << "Base - static void func()" << endl;
14     }
15 
16 
17 };
18 
19 int Base::m_A = 100;
20 
21 
22 class Son :public Base
23 {
24 public:
25     static int m_A;
26 
27     static void func()
28     {
29         cout << "Son - static void func()" << endl;
30     }
31 };
32 
33 int Son::m_A = 200;
34 
35 //同名静态成员属性
36 void test01()
37 {
38 
39     //1.通过对象方式 访问
40     cout << "通过对象方式访问: " << endl;
41     Son s;
42     cout << "Son-m_A = " << s.m_A << endl;
43 
44     cout << "Base-m_A = " << s.Base::m_A << endl;
45 
46 
47     //2.通过类名方式访问
48 
49     cout << "通过类名的方式访问:" << endl;
50     cout << "Son m_A = " << Son::m_A << endl;
51     //第一个::代表通过类名的方式访问  第二个::代表访问父类作用域下的
52 
53     cout << "Son m_A = " << Son::Base::m_A << endl;
54 
55 
56 }
57 
58 //同名静态成员函数
59 void test02()
60 {
61     //通过对象的方式访问
62     cout << "通过对象的方式访问:" << endl;
63     Son s;
64     s.func();
65 
66     s.Base::func();
67 
68     //通过类名的方式访问
69     cout << "通过类名的方式访问:" << endl;
70     Son::func();
71     Son::Base::func();
72 
73     
74 }
75 int main()
76 {
77 
78     //test01();
79     test02();
80 
81     system("pause");
82 
83     return 0;
84 
85 }

 

posted on 2021-08-08 11:21  Bytezero!  阅读(67)  评论(0编辑  收藏  举报