我正在阅读 C++ 文档教程,但在理解这个在构造函数中使用指针的示例时遇到了一些麻烦:
// example on constructors and destructors
#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;
}
似乎指针*width
被声明了两次。它在类的最开始声明:int *width, *height;
,并且在构造函数初始化时也声明width = new int;
。
为什么需要两次声明指针?