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

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

问题描述

很抱歉,复杂的标题。我有这样的:

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\n", 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

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天全站免登陆