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.
这篇关于用子类对象初始化的多态基类对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用子类对象初始化的多态基类对象数组
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
