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

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

 

  

#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;

}

 

相关文章:

  • 2021-08-29
  • 2022-03-10
  • 2021-07-05
  • 2022-12-23
  • 2022-12-23
  • 2022-02-21
  • 2022-12-23
猜你喜欢
  • 2021-11-16
  • 2022-12-23
  • 2021-11-08
  • 2022-12-23
  • 2022-12-23
  • 2021-09-11
相关资源
相似解决方案