相关疑难解决方法(0)

如何在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;
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试创建一个3表类的数组.要求是我必须使用Base对象来做到这一点.

Base1 * pBase …
Run Code Online (Sandbox Code Playgroud)

c++ arrays polymorphism virtual inheritance

7
推荐指数
3
解决办法
8835
查看次数

为什么这段代码会在提到的地方崩溃?

你能详细说明为什么这个代码在提到的地方崩溃了吗?我有点难过.我想这与它有关,sizeof(int)但我不太确定.谁能解释一下?

class Base
{
public:
    virtual void SomeFunction() 
    {
        printf("test base\n");
    }

    int m_j;
};

class Derived : public Base {
public:
   void SomeFunction() 
   {
       printf("test derive\n");
   }

private:
   int m_i;
};

void MyWonderfulCode(Base baseArray[])
{
   baseArray[0].SomeFunction();  //Works fine
   baseArray[1].SomeFunction();  //Crashes because of invalid vfptr
   baseArray[2].SomeFunction();  //Crashes because of invalid vfptr
   baseArray[3].SomeFunction();  //Works fine
   baseArray[4].SomeFunction();  //Crashes because of invalid vfptr
   baseArray[5].SomeFunction();  //Crashes because of invalid vfptr
   baseArray[6].SomeFunction();  //Works fine
   baseArray[7].SomeFunction();  //Crashes because of invalid vfptr
   baseArray[8].SomeFunction();  //Crashes because …
Run Code Online (Sandbox Code Playgroud)

c++ arrays virtual

5
推荐指数
4
解决办法
1202
查看次数

虚析构函数使用数组失败

我在网站上找到了这段代码

#include <iostream>

using namespace std;

struct Base
{
    Base() { cout << "Base" << " "; }
    virtual ~Base() { cout << "~Base" << endl; }

    int i;
};
struct Der : public Base
{
    Der() { cout << "Der" << endl; }
    virtual ~Der() { cout << "~Der" << " "; }

    int it[10]; // sizeof(Base) != sizeof(Der)
};

int main()
{
    Base *bp = new Der;
    Base *bq = new Der[5];

    delete    bp;
    delete [] …
Run Code Online (Sandbox Code Playgroud)

c++ polymorphism segmentation-fault new-operator virtual-destructor

5
推荐指数
1
解决办法
544
查看次数