Array of polymorphic base class objects initialized with child class objects(用子类对象初始化的多态基类对象数组)
问题描述
抱歉标题太复杂了.我有这样的事情:
Sorry for the complicated title. I have something like this:
class Base
{
public:
int SomeMember;
Base() : SomeMember(42) {}
virtual int Get() { return SomeMember; }
};
class ChildA : public Base
{
public:
virtual int Get() { return SomeMember*2; }
};
class ChildB : public Base
{
public:
virtual int Get() { return SomeMember/2; }
};
class ChildC : public Base
{
public:
virtual int Get() { return SomeMember+2; }
};
Base ar[] = { ChildA(), ChildB(), ChildC() };
for (int i=0; i<sizeof(ar)/sizeof(Base); i++)
{
Base* ptr = &ar[i];
printf("El %i: %i
", i, ptr->Get());
}
哪些输出:
El 0: 42
El 1: 42
El 2: 42
这是正确的行为吗(在 VC++ 2005 中)?老实说,我希望这段代码不会编译,但它确实编译了,但是它没有给我我需要的结果.这有可能吗?
Is this correct behavior (in VC++ 2005)? To be perfectly honest, I expected this code not to compile, but it did, however it does not give me the results I need. Is this at all possible?
推荐答案
是的,这是正确的行为.原因是
Yes, this is correct behavior. The reason is
Base ar[] = { ChildA(), ChildB(), ChildC() };
通过将三个不同类的对象复制到 class Base
的对象上来初始化数组元素,并产生 class Base
的对象,因此您可以观察到 class Base 的行为
来自数组的每个元素.
initializes array elements by copying objects of three different classes onto objects of class Base
and that yields objects of class Base
and therefore you observe behavior of class Base
from each element of the array.
如果你想存储不同类的对象,你必须用 new
分配它们并存储指向它们的指针.
If you want to store objects of different classes you have to allocate them with new
and store pointers to them.
这篇关于用子类对象初始化的多态基类对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用子类对象初始化的多态基类对象数组


- 从python回调到c++的选项 2022-11-16
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01