I have a question about pointer to a object in C++.
For example, if we have a CRectangle class and there is ay variable in it.
CRectangle *x = new CRectangle;
x->y
means member y of object pointed by x, what about (*x).y
? are they the same?
Yes, x->y
and (*x).y
are exactly the same in your example. The ->
means dereference X, and *x
means exactly the same.
Yes, (*x).y
is equivalent to x->y
if x
is of a pointer type.
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;
}
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.