2017-03-09 81 views
1

所以这里是一个例子,我想在功能main做什么。 例子,看我的评论的字里行间:呼叫父级的公共成员函数以外的类

#include <stdio.h> 

class A { 
public: 
    void msg() 
    { 
     puts("from A"); 
    } 
}; 

class B : public A { 
public: 
    void msg() 
    { 
     puts("from B"); 
    } 
}; 

int main() 
{ 
    A a; 
    B b; 

    a.msg(); 
    b.msg(); // This must print out B 
    b.msg(); // And I want this to print A. What is the syntax for that? 
} 

我不想额外的代码添加到这一点,只是可能有些synthatic糖。像A::b.msg东西,但它没有工作

+1

使用'b.A :: msg();' –

+0

你想通过这样做来解决什么是*实际*和*原始*问题? –

回答

4

您可以使用以下方法:

b.A::msg(); //will call msg from the class A 

但是,也许你应该寻找在不同的模式?

+0

谢谢Jean-Bernard。 –