-5
  #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”。有人可以指出错误。

4

3 回答 3

2

这里:

Crectangle::Crectangle()
{
  *height=3; // height could point anywhere
  *width=5;  // width could point anywhere
}

您正在取消引用未初始化的指针。这是未定义的行为,因此结果可能是任何东西。

解决方案是不要使用指针 forheightwidth。似乎没有任何理由使用它们。

class Crectangle
{
    int height;
    int width;
 ....
};
于 2013-05-04T08:06:23.510 回答
1

只有一个构造函数为宽度和高度分配内存。另一个具有未定义的行为。

于 2013-05-04T08:06:36.607 回答
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();
}
于 2013-05-07T17:31:43.427 回答