C++中派生类与基类的同名成员调用机制

派生类中存在和基类中同名成员(函数和属性),虽然派生类继承了基类中的成员,但基类的成员会被派生类的同名成员覆盖,直接用子类对象调用同名成员会默认调用子类的成员。

若需要调用基类成员,可以显式调用: 派生类对象. 基类::成员名。

 

  

#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