2010-07-19 162 views
1

我有一个类,像这样:C++继承问题

class A 
{ 
    public: 
     virtual void foo() { bar() } 

    protected: 
     virtual void bar() { /* do stuff */ } 
} 

现在我想一个派生类B中会覆盖foo和酒吧。所以我写了以下内容:

class B : public A 
{ 
    public: 
     virtual void foo() { A::foo(); /* then other stuff */ } 

    protected: 
     virtual void bar() { /* do different stuff */ } 
} 

一切编译,但是当我调用B :: foo的我希望B ::酒吧得到(最终)调用。相反,我得到A :: bar。我究竟做错了什么?

+3

您忘了将所有指针增加42. – 2010-07-19 16:51:41

+1

您是如何声明您的“B”实例的? – reuscam 2010-07-19 16:52:09

+1

您能告诉我们您是如何调用它们的吗? – Tom 2010-07-19 16:52:24

回答

2

由操作员更新之前。

这应该工作

A* b = new B(); 

b->bar(); //Notice that this is just an example 

还与引用

工作
void B::foo(){this->bar();} 

    B b; 
    A& ab = b; 
    ab.foo(); //calls B::bar() 
+1

您的更新没有任何意义。如果他*明确地调用了'A :: bar',这将是正确的(尽管'this->'仍然是多余的),但是再看看他的代码:他明确地调用了'A :: foo',依次调用'bar()'。由于'bar'是虚拟的,因此它应该像他所期望的那样解析为'B :: bar'。 – 2010-07-19 17:11:46

+0

好吧然后即时将它取出 – Tom 2010-07-19 17:18:03

+1

b-> bar()将不会工作,因为该成员受保护。您对B :: foo()的重新定义不是OP想要的。他希望它首先调用A :: foo()的基本实现。 – 2010-07-19 17:39:53

9

一切编译,但是当我调用B :: foo的我希望B ::酒吧得到(最终)调用。相反,我得到A :: bar。我究竟做错了什么?

看起来你并没有真正理解了什么错在你的原代码,决定虚拟控机制必须是罪魁祸首,然后你张贴了非工作示例描述你是什么倾向于相信,但你没有打扰检查,因为如果你有,那么你看到它不公开所描述的行为。这是你的例子的可编译版本。

#include <stdio.h> 
class A 
{ 
    public: 
     virtual void foo() { puts("A:foo()"); bar(); } 

    protected: 
     virtual void bar() { puts("A:bar()"); } 
}; 

class B : public A 
{ 
    public: 
     virtual void foo() { puts("B:foo()"); A::foo(); } 

    protected: 
     virtual void bar() { puts("B:bar()"); } 
}; 


int main() 
{ 
    B b; 
    b.foo(); 
} 

当我运行此我得到:

$ g++ g++ h.cc 
$ ./a.out 
B:foo() 
A:foo() 
B:bar() 

所以,一切都很好用B ::巴()。

+1

确实。问题在于创建对象的代码并调用函数(我们未显示)或解释结果。 – 2010-07-19 17:40:28

0

除了类定义末尾缺失的分号以外,当前的OP代码按预期工作。