【问题标题】:Is it possible that we can call the parent's class method through a child class in main method?是否可以通过main方法中的子类调用父类的方法?
【发布时间】:2021-11-27 07:02:51
【问题描述】:

我创建了一个程序,其中有两个班级,即母亲和女儿。女儿班继承自母亲班。这两个类具有相同的方法名称,但它们打印不同的数据。现在在 main 方法中,我创建了一个子类的对象,并通过女儿的对象调用了 display(),它覆盖了母亲的 display() 方法。

现在我想通过女儿的对象在main方法中调用妈妈的display()方法,那怎么做呢?可以这样做吗?

我尝试过这样做,但它显示错误(请参阅最后第 3 行代码)

#include <iostream>

using namespace std;

class mother{
    public:
    void display(){
        cout<<"Mother"<<endl;
    }
};
class daughter : public mother{
    public:
    void display(){
        cout<<"Daughter"<<endl;
    }
};

int main(){
    daughter rita;
    mother mother;
    rita.display();
    mother::rita.display(); //error
    return 0;
}

【问题讨论】:

标签: c++


【解决方案1】:

你们很亲密。

rita.mother::display();

https://ideone.com/WZ7j8C

【讨论】:

  • 我试过了,效果很好!谢谢朋友!
猜你喜欢
  • 2017-08-12
  • 2016-02-14
  • 2014-04-29
  • 2023-03-14
  • 2017-10-12
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
  • 2017-11-09
相关资源
最近更新 更多