[英]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;
}
如何正確指的是x
和y
的變量struct A
,而不是x
和y
的構造函數的參數變量的A
?
謝謝。
this
是一個指針,所以你需要取消引用它:
this->x = x;
this->y = y;
它是一個struct
或class
是無關緊要的,它在兩種情況下都是一個指針。 兩者之間唯一不同的是,默認情況下, struct
成員是public
的,而class
成員默認是private
的。
此外,在函數內部定義struct
或class
並不是一個好主意。 改為在全球范圍內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.