派生类中存在和基类中同名成员(函数和属性),虽然派生类继承了基类中的成员,但基类的成员会被派生类的同名成员覆盖,直接用子类对象调用同名成员会默认调用子类的成员。
若需要调用基类成员,可以显式调用: 派生类对象. 基类::成员名。
#include <iostream>
using namespace std;
class Parent
{
public:
Parent(int A)
{
this->a = A;
}
virtual void print()
{
cout << "a=" << a<<endl;
}
private:
int a;
};
class Child :public Parent
{
public:
Child(int B) :Parent(10)
{
this->b = B;
}
void print()
{
cout << "b=" << b << endl;
}
private:
int b;
};
int main()
{
Child mychild(20);
mychild.Parent::print();结果为:a=10;
mychild.print();//结果为:b=20;
}
原文链接: https://www.cnblogs.com/lyjbk/p/12834642.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/196985
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!