3

我有一个这样定义的类:

class MyClass 
{
    int x;
    public: 
        MyClass(int x); 
};

MyClass::MyClass(int x)
{ //Assign x here 
}

但是,我无法x在构造函数中进行初始化,因为它与实例变量具有相同的名称。有没有办法解决这个问题(除了更改参数的名称)?

4

9 回答 9

13

最好的选择是使用构造函数的初始化列表:

MyClass::MyClass(int x) : x( x ) { // Body }

但您也可以尝试这种方法:

MyClass::MyClass(int x) { this->x = x; }
于 2010-02-02T19:41:32.427 回答
9

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)?

So change the name of the parameter!

class MyClass  
{ 
    int x; 
    public:  
        MyClass(int xInitVal);  
}; 

MyClass::MyClass(int xInitVal)
    :x(xInitVal)
{ // Don't assign x here.  
} 

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.

于 2010-02-02T19:55:30.293 回答
3

顺便说一句 - 你真的应该为你的成员变量有一个不冲突的命名约定。这通常是 c++ 房屋的编码规则 1 或 2。然后当你看到 m_foo = bar 你就知道到底发生了什么

我们用

 int m_thingy;

我也看过

 int _thingy;
 int thingy_

如果您知道这一点并且不能或不会这样做,请提前道歉

于 2010-02-02T19:45:04.917 回答
2

您可以使用this显式引用当前对象:

this->x = x;
于 2010-02-02T19:41:50.087 回答
2

this->x = x;

于 2010-02-02T19:41:30.400 回答
1

我强烈建议您只更改变量名称。使用重复的标识符是一场没有原因的斗争。

在我的代码中,我给所有函数参数加上前缀“in”(“inValue”)。我给所有私有成员变量加上前缀“m”(“mValue”)。

于 2010-02-02T20:54:17.973 回答
0

使用 this 指针

MyClass::MyClass(int x)
{
    this->x = x;
}

当然,首先没有这样的冲突名称将是一个更好的解决方案。

于 2010-02-02T19:42:27.340 回答
0

this->x = x 不工作?这就是我们所做的(或使用了不同的参数名称)。

于 2010-02-02T19:43:28.210 回答
0

改为使用this->x

于 2010-02-02T19:41:30.587 回答