2013-05-04 66 views
-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」。有人可以指出錯誤嗎?構造函數重載。得到錯誤的解決方案

+0

爲什麼高度和寬度指針?你的默認構造函數是錯誤的,因爲它永遠不會爲高度或寬度分配空間。直接使用ints,如果你想使用默認值,只需使用'Crectangle :: Crectangle(int a = 3,int b = 5);' – Corbin 2013-05-04 08:06:07

回答

1

只有一個構造函數爲寬度和高度分配內存。另一個有未定義的行爲。

+0

感謝您的回覆。 – aghoribaba 2013-05-04 08:11:57

2

這裏:

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

你解引用未初始化的指針。這是未定義的行爲,所以結果可能是任何東西。

解決方案是不使用指針heightwidth。無論使用它們,似乎都沒有任何理由。

class Crectangle 
{ 
    int height; 
    int width; 
.... 
}; 
+0

ya,我知道,我可以在不使用指針的情況下完成該任務,但是我只是想用它們來做。無論如何,現在我知道我錯了。 – aghoribaba 2013-05-04 08:15:33

+1

如果您使用指針,則必須實現或禁用賦值(operator =)。 – 2013-05-04 08:28:17

+2

也複製構造函數 – john 2013-05-04 08:41:10

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(); 
}