0

我现在正在研究继承。我有一个名为 Shape 的基类,其他几个子类。没有编译错误。但是当我输入所有坐标后,会弹出分割错误。在驱动程序类中,当我尝试使用此 d[count].toString(); 时的选项

形状.h

class Shape
{
  protected:
     string name;
     bool containsWarpSpace;

  public:
    Shape();
    Shape(string, bool);
    string toString();
    virtual double computeArea();
    void setName (string);
    // some other codes here
 };

平方.h

class Square : public Shape
{
protected:
    int *x;
    int *y;
    int area;
    int vertices;

public:
    double computeArea();
    void setSquare(string, string, int*, int*);
    string toString();

};

正方形.cpp

void Square::setSquare(string name, string type, int* a, int* b)
{
setName(name);
setContainsWarpSpace (type);
vertices = 4;
x = new int[vertices];
y = new int[vertices];

for (int i = 0; i < vertices; i++)
{
    x[i] = a[i];
    y[i] = b[i];
}


}

string Square::toString()
{
    ostringstream convert;
    string s;
string type;

for (int i = 0; i < vertices; i++)
{
    convert << "point " << i + 1 
        << " ( "            
        << x[i] << " , " << y[i] 
        << " ) "<< endl;
}
 s = convert.str();

return s;

}

带 int main() 的驱动程序类

class Driver
 {
public:
    Driver();
    Shape *d[];
    Square *s;      

    int count;
    int noSquare;
    int noRectangle;
    int noCross;

    void printDetails();
    void printPlan();
    void option1();
    void option2();
    void option3();
    void option4();
    string convertString(string);

 };

驱动程序.cpp。这是默认构造函数,

Driver :: Driver()
{
Shape d [MAX];
s = new Square [MAX];
count = 0;
int noSquare = 0;
int noRectangle = 0;
int noCross = 0;
  }


  Driver::option1()
   {

if (shape.compare("square") == 0)
{
    tempx = new int[4];
    tempy = new int[4];

    for (int i = 0; i < 4; i++)
    {
        int j = i + 1;
        cout << "Please enter x-ordinate of pt " << j << ": ";
        cin >>tempx[i];        

        cout << "Please enter y-ordinate of pt " << j << ": ";
        cin >>tempy[i];      

    }

    s[noSquare].setSquare(shape,type, tempx,tempy);

    d[count] = &s[noSquare];
            d[count].toString();    



}
}


int main ()
{
    option1();


}
4

1 回答 1

0

更改您在 Driver 类中声明形状的方式。在标题中,将其声明为:

Shape* d;

并在您的 CPP 中对其进行初始化:

d = new Shape[MAX];

此外,由于您正在执行继承、数组和指针,因此您应该管理自己的析构函数。因为如果 chil 对象被销毁,它将使用父析构函数。因此,您的析构函数应该是:

virtual ~Shape();

和正方形:

virtual ~Square();

在其中,删除指针:

delete x; // in case of square
delete y;

当你有数组时:

delete [] d; // in case of driver class

否则它将无法正确释放内存。那可能会解决你的问题。

于 2013-11-05T14:17:45.437 回答