简体   繁体   中英

Pointers to classes

Looking at example under " Pointers to classes " (very bottom)

How is it that we can use the dot operatior here:

CRectangle * d = new CRectangle[2];
...
d[1].set_values (7,8);

if d is a pointer?

Same question for the lines:

  cout << "d[0] area: " << d[0].area() << endl;
  cout << "d[1] area: " << d[1].area() << endl;

Also, For the declaration:

  CRectangle * d = new CRectangle[2];

We can just declare a pointer to the type without declaring an object first?

d is a pointer to an array of CRectangle objects (2 in this case). d[i] is the i'th CRectangle object. so when you say d[i].set_values(), you are really calling the set_values method on the i'th CRectangle object in that array.

In this case, the pointer is actually an array, with two objects in it's construction. First "d" is constructed as an array with 2 elements:

CRectangle * d = new CRectangle[2];
// which is the dynamically allocated version of..
CRectangle d[2];

Then, it accesses the 2nd element's area() method via:

d[1].area()

In your example, while d is indeed a pointer, d[1] is not. It is a reference to the object at *(d+1) .

  1. The '.' is used as opposed to the de-reference '->' because while d is a pointer the objects to which it points are indeed not pointers, thus the d[1] returns a non-pointer object which is 'local'.
  2. The new operator in this sense works because the CRectangle class has a default constructor, however in the case where no default constructor is available this is not possible. What happens is new allocates space for two rectangle objects each of which is constructed via their default constructor.

Thought I'd just add the case where you would use the '->' operator:

CRectangle* d[2];
d[0] = new CRectangle();
d[1] = new CRectangle();
d[0]->set_values(7,8);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM