#include <iostream>
#include <conio.h>
using namespace std;
class Crectangle {
int * height, * width;
public: Crectangle();
Crectangle(int, int);
Crectangle();
int area() {
return (*height * *width);
}
};
Crectangle::Crectangle() {
*height = 3;
*width = 5;
}
Crectangle::Crectangle(int a, int b) {
height = new int;
width = new int;
*height = a;
*width = b;
}
Crectangle::~Crectangle() {
delete height;
delete width;
}
int main() {
Crectangle rect(1, 2);
Crectangle rectb;
cout << "rect = " << rect.area() << "\n";
cout << "rectb = " << rectb.area();
getch();
}
我得到的區域爲「6」,而不是「2」。有人可以指出錯誤嗎?構造函數重載。得到錯誤的解決方案
爲什麼高度和寬度指針?你的默認構造函數是錯誤的,因爲它永遠不會爲高度或寬度分配空間。直接使用ints,如果你想使用默認值,只需使用'Crectangle :: Crectangle(int a = 3,int b = 5);' – Corbin 2013-05-04 08:06:07