[英]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? 如果d是一个指针?
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是指向CRectangle对象数组的指针(在这种情况下为2)。 d[i] is the i'th CRectangle object.
d [i]是第i个CRectangle对象。 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.
因此,当您说d [i] .set_values()时,您实际上是在该数组中第i个CRectangle对象上调用set_values方法。
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:
第一个“ d”构造为具有2个元素的数组:
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: 然后,它通过以下方式访问第二个元素的area()方法:
d[1].area()
In your example, while d
is indeed a pointer, d[1]
is not. 在您的示例中,虽然
d
确实是一个指针,但d[1]
不是。 It is a reference to the object at *(d+1)
. 它是对
*(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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.