簡體   English   中英

在結構構造函數中使用“this”關鍵字編譯錯誤? - C ++

[英]Compile error with “this” keyword in a struct constructor? - C++

我有以下內容:

int main()
{
    struct A
    {
        unsigned char x, y;

        A(unsigned char x, unsigned char y)
        {
            this.x = x; // Error: expression must have class type.
            thix.y = y; // Error: expression must have class type.
        }
    };

    return 0;
}

如何正確指的是xy的變量struct A ,而不是xy的構造函數的參數變量的A

謝謝。

this是一個指針,所以你需要取消引用它:

this->x = x;
this->y = y;

它是一個structclass是無關緊要的,它在兩種情況下都是一個指針。 兩者之間唯一不同的是,默認情況下, struct成員是public的,而class成員默認是private的。

此外,在函數內部定義structclass並不是一個好主意。 改為在全球范圍內。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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