如何在 C++ 中分配给实例变量当局部变量具有相同名称时?
我有一个这样定义的类:
class MyClass
{
int x;
public:
MyClass(int x);
};
MyClass::MyClass(int x)
{ //Assign x here
}
但是,我无法在构造函数中初始化 x,因为它与实例变量具有相同的名称。有什么办法可以解决这个问题(除了更改参数名称之外)?
I have a class defined like this:
class MyClass
{
int x;
public:
MyClass(int x);
};
MyClass::MyClass(int x)
{ //Assign x here
}
However, I can't initialize x
in the constructor because it has the same name as an instance variable. Is there any way around this(other than changing the name of the argument)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
最好的选择是使用构造函数的初始值设定项列表:
但您也可以尝试这种方法:
The best option is to use the constructor's initializer list:
But you could also try this approach:
所以更改参数名称!
通过使参数名称与本地参数名称相同,只会使代码难以阅读。
不要这样做。几乎您遇到的每个样式指南都会告诉您不要使参数与成员同名。
So change the name of the parameter!
By making the parameter name the same as a local you are just making the code hard to read.
Don't do it. Nearly every style guide you come across will tell you not to make parameters the same name as members.
顺便说一句 - 你确实应该为你的成员变量制定一个不冲突的命名约定。这通常是 C++ House 的编码规则 1 或 2。 情况,
然后,当您看到 m_foo = bar 时,您确切地知道我们使用的
我也提前看到了道歉
如果您知道这一点并且不能或不会这样做,
as an aside - you really should have a naming convention for your member variables that does not clash. This is usually coding rules 1 or 2 for c++ houses. Then when you see m_foo = bar you know exactly what is going on
we use
I have also seen
apologies in advance if you knew this and could not or would not do it
这个->x = x;
this->x = x;
您可以使用
this
显式引用当前对象:You can use
this
to explicitly refer to the current object:我强烈建议您更改变量名称。弄乱重复的标识符是一场没有原因的战斗。
在我的代码中,我为所有函数参数添加前缀“in”(“inValue”)。我给所有私有成员变量添加前缀“m”(“mValue”)。
I strongly recommend you just change the variable names. Messing with duplicate identifiers is a fight without a cause.
In my code, I give all function parameters the prefix 'in' ("inValue"). I give all private member variables the prefix 'm' ("mValue").
请改用
this->x
。Use
this->x
instead.使用 this 指针
当然,首先不要有这样的冲突名称将是一个更好的解决方案。
Use the this pointer
Of course not having colliding names like that in the first place would be a better solution.
this->x = x 不起作用?这就是我们所做的(或使用不同的参数名称)。
this->x = x isn't working? That's what we did (or used a different parameter name).