아래 코드 조각은 정상적으로 작동합니다. 생성자와 소멸자포인터를 변수로 초기화해야하는 이유는 무엇입니까?
#include <iostream>
using namespace std;
class CRectangle {
int *width, *height;
public:
CRectangle (int,int);
~CRectangle();
int area() {return (*width * *height);}
};
CRectangle::CRectangle (int a, int b) {
width = new int;
height = new int;
*width = a;
*height = b;
}
CRectangle::~CRectangle() {
delete width;
delete height;
}
int main() {
CRectangle rect (3,4), rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
그런데 왜 나는 아래 대신 코드의 다른 부분을 사용하지 수에 는 // 예? 그것은 아래 코드를 사용하여 컴파일되지 않았지만 강제로 실행하면 올바른 결과가 생성됩니다. return (*width * *height);
코드
int area() {
return (*width * *height);
}
.
.
.
CRectangle::~CRectangle() {
delete width;
delete height;
}
의 두 번째 부분에서
#include <iostream>
using namespace std;
class CRectangle {
//here I didn't initialize these two variables' pointers.
int width, height;
public:
CRectangle (int a,int b);
~CRectangle();
int area() {
return (width * height);
}
};
CRectangle::CRectangle (int a, int b) {
width = a;
height = b;
}
CRectangle::~CRectangle() {
}
int main() {
CRectangle rect (3,4), rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
컴파일되지 않은 코드는 실행할 수 없습니다. 마지막으로 성공한 빌드를 실행하지 않았습니까? – chris
'width'와'height'는 포인터가 아니므로 직접 참조 부호를 사용하지 마십시오. 그리고 할당하지 않았기 때문에 삭제할 수 없습니다. – Barmar
@Barmar가 말한 것 중 가장 정확한 방법은 처음이 아니라 그것을 말하는 것입니다. – chris