簡體   English   中英

指向 C++ 中的 object 的指針

[英]the pointer to a object in C++

我對指向 C++ 中的 object 的指針有疑問。
例如,如果我們有一個 CRectangle class 並且其中有 y 變量。

CRectangle *x = new CRectangle;

x->y表示 x 指向的 object 的成員 y,那么(*x).y呢? 他們是一樣的嗎?

是的, x->y(*x).y在您的示例中完全相同。 ->表示取消引用 X, *x表示完全相同。

是的,如果x是指針類型, (*x).y等價於x->y

是的。 您可以使用此示例程序自行查看:

#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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM