用子类对象初始化的多态基类对象数组 [英] Array of polymorphic base class objects initialized with child class objects

查看:46
本文介绍了用子类对象初始化的多态基类对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉标题太复杂了.我有这样的事情:

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.

这篇关于用子类对象初始化的多态基类对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆