类的析构函数出错,请高手指点!
正在学习类的定义等,编写如下代码后运行出错,如果删除析构函数中释放内在的两条语句(红色标注),程序运行正常,不删除红色标注的语句会出错,看了许久也没发现问题,请高手指点!
/*
------------文件名:rectangle.h---------
作用:求面积的类的定义
观察类定义的方法,构造函数、析构函数的使用
*/
#ifndef RECTANGLE_H
#define RECTANGLE_H
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Crectangle {
public:
Crectangle ();
Crectangle (int,int); //构造函数
~Crectangle (); //析构函数
int area () {return (*width**height);};
Crectangle operator+(const Crectangle&);
void print_state(string);
void print_wh(Crectangle&);
private:
int *width, *height;
};
Crectangle::Crectangle()
{
width=new int;
height=new int;
*width=0;
*height=0;
print_state("运行空的构造函数");
}
Crectangle::Crectangle (int a, int b)
{ //构造函数定义
width = new int; //分配int型内存空间
height = new int;
*height = b; //将b放进内存
*width = a;
print_state("运行有值的构造函数");
}
Crectangle::~Crectangle () { //析构函数定义
delete width; //释放内存
delete height;
print_state("运行析构函数");
}
Crectangle Crectangle::operator+(const Crectangle& rect_temp)
{
Crectangle temp;
*temp.height=*rect_temp.height+*height;
*temp.width=*rect_temp.width+*width;
return temp;
}
void Crectangle::print_wh(Crectangle& rt)
{
cout <<*rt.height<<" "<<*rt.width<<endl;
}
void Crectangle::print_state(string str)
{
cout <<str<<endl;
}
#endif
主程序如下:
/*
------------文件名:rectangle.cpp---------
作用:求面积的类的定义
观察类的实例的定义及使用
*/
#include <iostream>
#include "rectangle.h"
using namespace std;
int main () {
Crectangle rect (3, 4), rectb (5, 6),rectc;
cout<<"rect area: "<<rect.area ()<<endl;
cout<<"rect area: "<<rectb.area ()<<endl;
rectc=rect+rectb;
rectc.print_wh(rectc);
cout<<"rect area: "<<rectc.area ()<<endl;
return 0;
}
[解决办法]
- C/C++ code
Crectangle::~Crectangle () { //析构函数定义 if(width != NULL)//加个判断如果不需要释放就不释放 delete width; //释放内存 if(height != NULL) delete height; print_state("运行析构函数");}
[解决办法]
因为你的类使用了自己分配的内存 应该定义拷贝构造和赋值操作符 否则用默认的拷贝会造成不同对象的width和height指向同一内存空间 在对象析构的时候导致double free
楼上的方法不能解决这个问题 除非delete之后同时把指针置零 不过即使这样也不是规范的做法
[解决办法]
内存非法导致的问题
[解决办法]
因为你没有定义行为良好的拷贝构造函数和赋值运算符。所以导致默认的在产生临时对象的时候将你new的内存释放了。
[解决办法]
需要定义一个赋值操作符