[英]the pointer to a object in C++
I have a question about pointer to a object in C++.我对指向 C++ 中的 object 的指针有疑问。
For example, if we have a CRectangle class and there is ay variable in it.例如,如果我们有一个 CRectangle class 并且其中有 y 变量。
CRectangle *x = new CRectangle;
x->y
means member y of object pointed by x, what about (*x).y
? x->y
表示 x 指向的 object 的成员 y,那么(*x).y
呢? are they the same?他们是一样的吗?
Yes, x->y
and (*x).y
are exactly the same in your example.是的, x->y
和(*x).y
在您的示例中完全相同。 The ->
means dereference X, and *x
means exactly the same. ->
表示取消引用 X, *x
表示完全相同。
Yes, (*x).y
is equivalent to x->y
if x
is of a pointer type.是的,如果x
是指针类型, (*x).y
等价于x->y
。
Yes.是的。 You can see it by yourself with this sample program:您可以使用此示例程序自行查看:
#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 r1, *r2;
r2= new CRectangle;
r1.set_values (1,2);
r2->set_values (3,4);
cout << "r1.area(): " << r1.area() << endl;
cout << "r2->area(): " << r2->area() << endl;
cout << "(*r2).area(): " << (*r2).area() << endl;
delete r2;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.