2014-02-15 86 views
0

我写了一个非常小的程序,使用类,继承和多态。在主要部分中,我已经使用new声明了一个指针,当我调用delete并调试程序时,它会崩溃。C++调试断言失败指针

反正这里是我的代码

#include <iostream> 
using namespace std; 

class Shape{ 
protected: 
    int height; 
    int width; 
public: 
    void getVal(int num1, int num2){ 
     height = num1; 
     width = num2; 
    } 
    int printVal(){ 
     return (width * height); 
    } 
}; 

class Rectangle: public Shape{}; 

int main(){ 
    Rectangle rec; 
    Shape* shape = new Rectangle; 
    shape = &rec; 
    shape ->getVal(2,2); 
    cout << "Your answer is: " << shape ->printVal() << endl; 
    delete shape; 
    system("pause"); 
    return 0; 
} 

谢谢

回答

1
Shape* shape = new Rectangle; 
shape = &rec; 

您在堆中分配一个对象,然后迅速泄漏它。 shape现在指向rec,一个自动对象。

delete shape; 

shape当前指向未分配与new,因此调用delete它具有未定义行为的对象。

+0

你能告诉我从我的代码,这将是很好@Igor Tandetnik – user3264250

+0

我应该怎么做才能够调用删除就可以了@Igor Tandetnik – user3264250

+0

你应该一)跌落'矩形REC;'和'形状= &rec; '线条,和b)给'形状'虚拟析构函数。 –