省流:与非静态成员处理方法一致


同名成员属性

代码示例

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
#include<iostream>
using namespace std;


class Base {
public:
static int m_A;

};

int Base::m_A = 100;

class son :public Base {
public:
static int m_A;
};
int son::m_A = 200;

int main() {
son s;
cout << "通过对象访问" << endl;
cout << "son 下 m_A=" << s.m_A << endl;
cout << "Base 下 m_A=" << s.Base::m_A << endl;
cout << "通过类名访问" << endl;
cout << "son 下 m_A=" << son::m_A << endl;
cout << "Base 下 m_A=" << son::Base::m_A << endl;
return 0;
}

同名成员函数

  • 如果子类中出现和父类同名的成员函数,子类的同名成员会隐藏掉父类中所有的同命成员函数
  • 如果访问到父类中被隐藏的同名成员函数,需要加作用域

代码示例

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
#include<iostream>
using namespace std;


class Base {
public:
static void func() {
cout << "Base - static void func()" << endl;
}
static void func(int a) {
cout << "son - static void func(int)" << endl;
}
};

class son :public Base {
public:
static void func() {
cout << "son - static void func()" << endl;
}
};

int main() {
cout << "通过对象访问" << endl;
son s;
s.func();
s.Base::func();
cout << "通过类名访问" << endl;
son::func();
son::Base::func();
cout << "重载" << endl;
son::Base::func(100);
return 0;
}