我有以下内容:
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;
}
如何正确引用 struct A
的 x
和 y
变量而不是 x
和A
的构造函数参数的y
变量?
谢谢。
最佳答案
this
是一个指针,因此您需要取消引用它:
this->x = x;
this->y = y;
它是struct
还是class
都没有关系,在这两种情况下它都是一个指针。两者唯一的区别是struct
成员默认是public
,而class
成员默认是private
.
此外,在函数内部定义struct
或class
也不是一个好主意。而是在全局范围内进行。
关于c++ - 在结构构造函数中使用 "this"关键字编译错误? - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35805056/