继承与分段错误

时间:2013-11-05 13:59:35

标签: c++

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

时的选项

Shape.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
 };

Square.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();

};

Square.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);

 };

Driver.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();


}

1 个答案:

答案 0 :(得分: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

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