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

"2"대신 "6"이 될 영역을 얻고 있습니다. 누군가 실수를 지적 할 수 있습니까? 여기생성자 오버로드. 잘못된 솔루션 얻기

+0

왜 높이 및 너비 포인터가 있습니까? 기본 생성자는 높이 또는 너비에 대한 공간을 할당하지 않으므로 잘못되었습니다. int를 직접 사용하고 기본값을 원한다면'Crectangle :: Crectangle (int a = 3, int b = 5);를 사용하십시오. – Corbin

답변

1

생성자 중 하나만 너비와 높이의 메모리를 할당합니다. 다른 하나는 정의되지 않은 동작을합니다.

+0

답장을 보내 주셔서 감사합니다. – aghoribaba

2

: 당신이 초기화되지 않은 포인터를 역 참조하는

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

. 이는 정의되지 않은 동작이므로 아무 것도 될 수 없습니다.

해결책은 heightwidth에 대한 포인터를 사용하지 않는 것입니다. 그 (것)들을 이용하는 아무 이유도다는 것을 보인다.

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

예, 포인터를 사용하지 않고 할 수 있었지만 단지 그들을 사용하여 그것을하고 싶었어요. 어쨌든 고마워, 내가 어디서 잘못되었는지 알아. – aghoribaba

+1

포인터를 사용하는 경우 할당 (연산자 =)도 구현하거나 사용하지 않도록 설정해야합니다. –

+2

복사 생성자 too – john

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