简体   繁体   English

类的指针

[英]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)处的对象的引用。

  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'. 相对于取消引用“->”,使用d是因为d是指针,但它指向的对象确实不是指针,因此d [1]返回的是“本地”非指针对象。
  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. 从这个意义上说,新操作符起作用是因为CRectangle类具有默认构造函数,但是在没有默认构造函数的情况下,这是不可能的。 What happens is new allocates space for two rectangle objects each of which is constructed via their default constructor. 发生的事情是new为两个矩形对象分配了空间,每个矩形对象都是通过其默认构造函数构造的。

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.

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