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)
.
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.