我有一个这样的类:
class A
{
public:
virtual void foo() { bar() }
protected:
virtual void bar() { /* do stuff */ }
}现在我想要一个同时覆盖foo和bar的派生类B。所以我写了以下内容:
class B : public A
{
public:
virtual void foo() { A::foo(); /* then other stuff */ }
protected:
virtual void bar() { /* do different stuff */ }
}一切都会编译,但当我调用B::foo时,我希望B::bar (最终)会被调用。相反,我得到的是A::bar。我做错了什么?
发布于 2010-07-20 01:33:04
一切都会编译,但是当我调用B::foo时,我希望B::bar (最终)会被调用。相反,我得到的是A::bar。我做错了什么?
看起来你并没有真正理解在你的原始代码中出了什么问题,决定虚拟覆盖机制一定是罪魁祸首,然后你发布了一个不起作用的例子,它描述了你倾向于相信,但你没有费心去检查,因为如果你已经检查了,那么你就会看到它没有暴露所描述的行为<代码>E211。以下是示例的可编译版本。
#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::bar()就没问题了。
发布于 2010-07-20 00:53:08
在被操作员更新之前。
这应该是可行的
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()发布于 2010-07-20 03:34:28
除了类定义末尾缺少的分号之外,当前的操作码可以正常工作。
https://stackoverflow.com/questions/3283109
复制相似问题