【发布时间】:2014-10-11 22:50:10
【问题描述】:
我有两个类,Object 和 Ball。 Ball派生自Object。对象有一个虚函数“move”和一个调用move的非虚函数“moveFast”。 Ball 类从它的父类重新定义了 move 函数。
#include <iostream>
struct Object
{
virtual void move(int dist)
{
std::cout<<"Moving "<<dist<<std::endl;
}
void moveFast(int multiplier)
{
move(10*multiplier);
}
};
struct Ball : public Object
{
void move(int dist)
{
std::cout<<"Rolling "<<dist<<std::endl;
}
};
class List
{
struct Node
{
Node* next;
Object ele;
Node(Object e, Node* n=NULL) : ele(e), next(n){}
};
Node* head;
public:
List() : head(NULL){}
void addObj(Object o)
{
if(head==NULL)
{
head = new Node(o);
return;
}
Node* current = head;
while(current->next!=NULL)
{
current=current->next;
}
Node* obj = new Node(o);
current->next=obj;
}
void doStuff()
{
Node* current = head;
while(current!= NULL)
{
current->ele.moveFast(10);
current=current->next;
}
}
};
int main()
{
Object a,b,c;
Ball d;
List list;
list.addObj(a);
list.addObj(b);
list.addObj(c);
list.addObj(d);
list.doStuff();
}
List 类接收对象并调用它们的 moveFast 函数。因为 a、b 和 c 只是对象,我希望前 3 行输出是“移动 100”。 然而,d 是 Ball 类的一个实例。所以我希望输出的第 4 行说“Rolling 100”,因为 Ball 重新定义了 move 函数。
现在所有的输出打印
Moving 100
Moving 100
Moving 100
Moving 100
有没有办法从 List 中获取 Ball 的移动定义?
【问题讨论】:
-
请编译器和版本。另外,请尝试以下完整程序(最好使用单个 .cpp 文件,以消除其他错误来源):coliru.stacked-crooked.com/a/346dc7763c73e410
-
您不需要通过
new在 C++ 中创建对象。在这种情况下,Ball b; foo(&b);就足够了。 -
你是在构造函数中调用它吗?如果是这样,请参阅stackoverflow.com/questions/496440/…
-
这不是一个实际的程序。只是我要问的概念的一个例子。类 A 作为一个虚成员函数 c 和一个非虚函数 d。函数 d 调用 c。然后从 A 派生的类 B 重新定义了虚函数 c。现在从 B 类的实例调用函数 d 时,如何让函数 d 调用 B 类的 c 定义。
-
“这不是一个实际的程序。” 这就是问题所在:您在此处显示的程序/代码不会重现该问题,它可能不包含相同的问题作为您实际使用的代码。可能会猜到您的真实代码使用了
void foo(Object o);并且存在切片问题。
标签: c++ polymorphism virtual