#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();
}
我将rect的区域设为“6”,而不是“2”。有人可以指出错误。
答案 0 :(得分:2)
下面:
Crectangle::Crectangle()
{
*height=3; // height could point anywhere
*width=5; // width could point anywhere
}
您正在取消引用未初始化的指针。这是未定义的行为,因此结果可能是任何结果。
解决方案是不使用height
和width
的指针。似乎没有任何理由使用它们。
class Crectangle
{
int height;
int width;
....
};
答案 1 :(得分:1)
只有一个构造函数为宽度和高度分配内存。另一个有不确定的行为。
答案 2 :(得分:0)
#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 = new int;
width = new int;
*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();
}