【问题标题】:How can a subclass call a method of the superclass with the same method name of the subclass?子类如何调用与子类方法名相同的超类方法?
【发布时间】:2011-06-09 09:48:08
【问题描述】:
#include <iostream>
using namespace std;

class Person {
public:
    void sing();
};

class Child : public Person {
public:
    void sing();
};

Person::sing() {
    cout << "Raindrops keep falling on my head..." << endl;
}

Child::sing() {
    cout << "London bridge is falling down..." << endl;
}

int main() {
    Child suzie;
    suzie.sing(); // I want to know how I can call the Person's method of sing here!

    return 0;
}

【问题讨论】:

标签: c++


【解决方案1】:
suzie.Person::sing();

【讨论】:

  • Person&amp; sue = suzie; sue.sing();
  • static_cast&lt;Person&amp;&gt;(suzie).sing();或其任何变体,是的。
  • 我写了那个然后删除了它。我尝试从不使用可以进行隐式转换的强制转换。
【解决方案2】:

孩子可以使用 Person::sign()。

请参阅 http://bobobobo.wordpress.com/2009/05/20/equivalent-of-keyword-base-in-c/ 以获得很好的解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-24
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    相关资源
    最近更新 更多