下面的这段代码工作正常。// 构造函数和析构函数的例子
#include <iostream>
using namespace std;
class CRectangle {
int *width, *height;
public:
CRectangle (int,int);
~CRectangle ();
int area () {return (*width * *height);}
};
CRectangle::CRectangle (int a, int b) {
width = new int;
height = new int;
*width = a;
*height = b;
}
CRectangle::~CRectangle () {
delete width;
delete height;
}
int main () {
CRectangle rect (3,4), rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
但是为什么我不能使用下面的另一段代码呢?它没有使用下面的代码编译,但如果我强制运行它仍然会生成正确的结果。
#include <iostream>
using namespace std;
class CRectangle {
//here I didn't initialize these two variables' pointers.
int width, height;
public:
CRectangle (int a,int b);
~CRectangle ();
int area () {
return (width * height);
}
};
CRectangle::CRectangle (int a, int b) {
width = a;
height = b;
}
CRectangle::~CRectangle () {
}
int main () {
CRectangle rect (3,4), rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}