0
点赞
收藏
分享

微信扫一扫

子类与父类的同名静态成员的调用与访问(和非静态规则一样,多出用类名访问的方式)

蒸熟的土豆 2022-02-25 阅读 49
class Father {//父类
public:
	Father() {
	}

	static void func() {
		cout << "father::func()" << endl;
	}
	static void func(int p) {
		cout << "father::func(int p)" << endl;
	}
	
	static int a;
};
int Father::a = 100;

class Son :public Father{//子类
public:
	Son() {
	}

	static void func() {
		cout << "son::func()" << endl;
	}
	static int a;
};
int Son::a = 200;

void test() {//通过对象调用
	Son son;
	cout << son.a << endl;
	cout << son.Father::a << endl;

	son.func();
	son.Father::func();
	son.Father::func(100);

    //通过类名调用
	cout << Son::a << endl;
	cout << Son::Father::a << endl;//表示通过类名访问父类的静态成员
	cout << Father::a << endl;

	Son::func();
	Son::Father::func();//表示通过类名访问父类的静态成员
	Father::func();

	
}

int main() {
	test();
}

/*
结果:
200
100
son::func()
father::func()
father::func(int p)
200
100
100
son::func()
father::func()
father::func()
*/
举报

相关推荐

0 条评论