问题描述
好吧,我正在编写一个游戏,其中包含一个副驾驶级别(敌人)的矢量,这个游戏将充满儿童课程(goomba,koopa,boss1),当我打电话给我更新时,我需要这样做调用子类各自的更新。我设法创建了一个问题的例子。
Okay, I'm writing a game that has a vector of a pairent class (enemy) that s going to be filled with children classes (goomba, koopa, boss1) and I need to make it so when I call update it calls the childclasses respective update. I have managed to create a example of my problem.
#include <stdio.h>
class A{
public:
virtual void print(){printf("Hello from A");}
};
class B : public A{
public:
void print(){printf("Hello from B");}
};
int main(){
A ab = B();
ab.print();
while(true){}
}
输出通缉:你好来自B
输出得到:你好A
Output wanted: "Hello from B"Output got: "Hello from A"
如何让它调用B的打印功能?
How do I get it to call B's print function?
推荐答案
多态性仅适用于指针和引用。如果您将 B
分配给 A
,则 A
,您将丢失所有 B
特定信息,包括方法覆盖。这称为切片; B
部分在分配给父类的对象时从对象中切片。
Polymorphism only works on pointers and references. If you assign a B
to an A
, it becomes an A
and you lose all B
-specific information, including method overrides. This is called "slicing"; the B
parts are "sliced" off the object when it is assigned to an object of a parent class.
另一方面,如果您将 B *
分配给 A *
,则看起来喜欢 A *
,但仍然指向 B
,所以 B
- 特定信息仍然存在,并且将使用 B
的虚拟覆盖。
On the other hand, if you assign a B*
to an A*
, it looks like an A*
, but is still really pointing to a B
, and so the B
-specific information remains, and B
's virtual overrides will be used.
尝试:
int main(){
A* ab = new B();
ab->print();
delete ab;
while(true){}
}
这同样适用于分配a B
到 A&
(引用 - A
),例如
The same also applies to assigning a B
to an A&
(reference-to-A
), e.g.
int main(){
B b;
A& ab = b;
ab.print();
while(true){}
}
这篇关于问题覆盖虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!