继承同名静态成员的处理方式

#include
using namespace std;
class Base {
public:
	static int m_A;
	static void func() {
		cout << "Base-static void func" << endl;
	}
 };	
int Base::m_A=100;

class son :public Base
{
public:
	static int m_A;
	static void func() {
		cout << "son-static void func" << endl;
	}
};
int son::m_A = 200;
//同名静态成员属性
void test01() {
	//1.通过对象访问
	son s;
	cout << s.m_A << endl;
	cout << s.Base::m_A << endl;
	//2.通过类名访问(不需要创建对象)
	cout << son::m_A << endl;
	cout << Base::m_A << endl;
	cout << son::Base::m_A << endl;//这个挺重要
}//第一个::表示要通过类名的方式来访问一个数据,通过类名的方式访问父类作用域(第二个::)的m_A;
//同名静态成员函数属性
void test02()
{
	//1.通过对象访问
	son s;
	s.func();
	s.Base::func();
	//2.通过类名访问
	son::func();
	son::Base::func();
}
int main() {
	test01();//直接访问选子类-200
	test02();
}

如果你的代码迷之打不出来,可能是你只写了son::func;忘记加()......

你可能感兴趣的:(c++)