c++ - 对象数组的变量类型

标签 c++ pointers

我对以下取自 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/

相关文章:

c - strtok() 覆盖它的源字符串

pointers - 从指针中获取值

c++ - 暂停 boost::thread 无限时间

c++ - 为什么我会收到编译器错误,尽管大小是常量?

c++ - Mathematica/CUDA 减少执行时间

c++ - ostream operator<< 为采用 STL 容器而重载,传递 std::string 会破坏它吗?

c++ - 在 Symbian C++ 中将 unsigned char* 转换为 const TDesC8

c - C 中指针递增的方法有很多种,有什么区别?

c - 理解 strtok 返回的指针

c++ - 关于 auto_ptr::reset 的问题