2

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()とは対照的になぜ合法なのかを考えていたところ、これが私をwhered[0]->area()の減速に導きました。new はポインターを返し、それは配列であるためポインターへのポインターであるため (したがって [])、2 つのレベルの間接参照はありません。言い換えれば、そうではありませんか?dCRectangle * d = new CRectangle[2];dCRectangle ** d**=*[]

4

2 に答える 2

2

CRectangle * d = new CRectangle[2];dへのポインターとして宣言し、 CRectangle2 つのオブジェクトを含む配列の最初のオブジェクトを指すように初期化しCRectangleます。したがって、へのポインタではなくd[0]、型があります。これが、ドット演算子 (.) の使用が合法である理由です。CRectangleCRectangle

于 2013-07-08T19:56:49.760 に答える
1

為に:

CRectangle *d = new CRectangle[2];

(おおむね) 同等です (決して、これまでに、これを行うことはありません。new を使用するだけです):

CRectangle *d = (CRectangle*)malloc(2*sizeof(CRectangle));
... plus some default construction ...

d はポインタです。d[0] はポインタではなく、配列インデックス 0 の値です。

*(d + n)d[n] は、配列 d の位置 'n' にある値 (したがって逆参照 *) の省略形です。の戻り値はnew CRectangle[2]ですCRectangle*

配列は次のようにメモリに格納されます。

       d[0] [1] [2] [3] [4] [5] [6] [7] ...
値 ABCDEFGH ...
オフセット: 0 +1 +2 +3 +4 +5 (もちろん x sizeof(CRectangle))...
于 2013-07-08T19:56:41.593 に答える