如何使多态性在C ++中数组? [英] How to make an array with polymorphism in C++?

查看:149
本文介绍了如何使多态性在C ++中数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Base1
{
    private:
     int testInput; 
    public:
       Base1();
       virtual int GetRow(void) = 0;
 };

 Base1::Base1()
 {
   testInput = 0;
 }

class table : public Base1
{
   private:
    int row;    
   public:  
     table();
     virtual int GetRow(void);
};

table::table()
{   
  //Contructor
  row = 5;
}

int table::GetRow()
{
  return row;
}

int main ()
{
  Base1* pBase = new table[3];
  pBase[0].GetRow();
  pBase[1].GetRow();   //when i get to  this line, the compiler keep saying access
                           // violation.
  pBase[2].GetRow();

  return 0;
}

我试图创建3个表类的数组。要求是我必须使用的基本对象做到这一点。

I'm trying to create an array of 3 table class. The requirement is I have to use Base object to do that.

Base1 * pBase = new table[3];  

看没什么问题。但是,当我试图访问的每个表,编译器说,它的访问冲突。我不知道自己做错了什么与此code。我使用Visual Studio 2010中虽然。

look fine to me. But when I tried to access each table, the compiler said it's access violation. I don't know what wrong with this code. I'm using Visual Studio 2010 though.

推荐答案

在C ++中,多态性和数组不要混用。

由于一般的派生类的大小是基类,多态和指针算法不很好地一起玩的大小不同。由于数组访问涉及指针运算,前pressions如 PBASE [1] 不正常工作。

Since in general the size of the derived class is different to the size of the base class, polymorphism and pointer arithmetic don't play together nicely. Since array access involves pointer arithmetic, expressions such as pBase[1] don't work as expected.

一种可能性是拥有的指针的给你的对象,甚至是智能指针,以简化内存管理的阵列。但不要忘了在 BASE1 来定义一个虚析构函数。

One possibility is to have an array of pointers to your objects, perhaps even smart pointers to simplify memory management. But don't forget to define a virtual destructor in Base1.

这篇关于如何使多态性在C ++中数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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