如何在 C++ 中创建具有多态性的数组? [英] How to make an array with polymorphism in C++?

查看:51
本文介绍了如何在 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 个表类的数组.要求是我必须使用 Base 对象来做到这一点.

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];  

对我来说很好.但是当我尝试访问每个表时,编译器说这是访问冲突.我不知道这段代码有什么问题.不过,我使用的是 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++ 中,多态和数组不能混用.

由于派生类的大小通常与基类的大小不同,因此多态性和指针运算不能很好地结合在一起.由于数组访问涉及指针算术,诸如 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天全站免登陆