Rub*_*ben 0 c++ constructor struct this
一个简短的,也许是愚蠢的问题.对于类和结构,有时我喜欢使用与构造函数参数同名的成员变量.例如:
class Vector3
{
float x, y, z;
public Vector3(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,我也想为结构做这个,但你不能在结构构造函数中使用'this'(我认为它们的使用是为类保留的).有没有办法做到这一点,还是我应该给我的论点另一个名字?
你可以使用它,但它的指针就像在类中一样:
this->x = x;
Run Code Online (Sandbox Code Playgroud)
顺便说一下,a struct和a class对于除了默认访问说明符之外的所有内容完全相同.
你真正应该做的是使用构造函数的初始化列表:
class Vector3
{
float x, y, z;
public:
Vector3(float x, float y, float z) : x(x), y(y), z(z) {}
};
Run Code Online (Sandbox Code Playgroud)
但是关于你this在结构中使用的疑虑,一个类没有区别.
我想补充一点,确实值得为数据成员设置某种命名约定,以避免混淆.收藏夹往往是尾随下划线或前导m_.