0
点赞
收藏
分享

微信扫一扫

子类与父类的同名成员调用和注意事项

星巢文化 2022-02-25 阅读 214
class Father {//父类
public:
	Father() {
		a = 100;
	}

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

class Son :public Father{//子类
public:
	Son() {
		a = 200;
	}

	void func() {
		cout << "son::func()" << endl;
	}
	int a;
};


void test() {
	Son son;
	cout << son.a << endl;//同名成员属性,子类直接调用为子类自身的成员
	cout << son.Father::a << endl;//加上父类作用域后,子类调用的是父类的成员
	son.func();//同名成员函数,子类直接调用为子类自身的成员
	son.Father::func();//加上父类作用域后,子类调用的是父类的成员
	son.Father::func(100);
	//当子类与父类有同名成员函数后,父类的重载函数,将被隐藏,需要加上父类作用域后才可以调用
}

int main() {
	test();
}

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

相关推荐

0 条评论