我对以下取自 cplusplus.com 的示例感到困惑
// pointer to classes example
#include <iostream>
using namespace std;
class CRectangle {
int width, height;
public:
void set_values (int, int);
int area (void) {return (width * height);}
};
void CRectangle::set_values (int a, int b) {
width = a;
height = b;
}
int main () {
CRectangle a, *b, *c;
CRectangle * d = new CRectangle[2];
b= new CRectangle;
c= &a;
a.set_values (1,2);
b->set_values (3,4);
d->set_values (5,6);
d[1].set_values (7,8);
cout << "a area: " << a.area() << endl;
cout << "*b area: " << b->area() << endl;
cout << "*c area: " << c->area() << endl;
cout << "d[0] area: " << d[0].area() << endl;
cout << "d[1] area: " << d[1].area() << endl;
delete[] d;
delete b;
return 0;
}
我在想为什么 d[0].area()
是合法的,而不是 d[0]->area()
这让我想到了d
的减速度,其中 CRectangle * d = new CRectangle[2];
。是否存在两级间接寻址,因此不应该使用 CRectangle ** d
声明 d
因为 new 返回一个指针,并且它是一个指向指针的指针,因为它是一个数组(因此是[])。换句话说,**=*[]
不是吗?
最佳答案
CRectangle * d = new CRectangle[2];
将 d
声明为指向 CRectangle
的指针,并将其初始化为指向第一个对象包含两个 CRectangle
对象的数组。因此,d[0]
的类型为 CRectangle
,不是指向 CRectangle
的指针。这就是为什么使用点运算符 (.) 是合法的。
关于c++ - 对象数组的变量类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17534851/