开发者

the pointer to a object in C++

开发者 https://www.devze.com 2023-03-03 16:33 出处:网络
I have a question about pointer to a object in C++. For example, if we have a CRectangle class and there is a y variable in it.

I have a question about pointer to a object in C++.

For example, if we have a CRectangle class and there is a y variable in it.

CRectangle *x =开发者_如何学Python 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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消