成员名称和构造函数名之间的冲突

问题描述:

可能重复:结果
  成员VS方法的参数用C ++访问

我有了一些成员,如 X 宽度类高度。在它的构造,我不会做这样的:

I have a class that has some members, like x, y, width and height. In its constructor, I wouldn't do this:

A::A(int x, int y, int width, int height)
{
    x = x;
    y = y;
    width = width;
    height = height;
}

这并没有什么意义,当与G ++ X 宽度高度成为怪异的值(如 -1405737648 )。

This doesn't really make sense and when compiled with g++ x, y, width, and height become weird values (e.g. -1405737648).

什么是解决这些命名冲突的最佳方式?

What is the optimal way of solving these naming conflicts?

您可以使用初始化列表就好具有相同的名称:

You can use initialization lists just fine with the same names:

A::A(int x, int y, int width, int height) :
    x(x),
    y(y),
    width(width),
    height(height)
{
}

另一种方法是使用不同的名称,如果不希望有相同的名称。一些匈牙利表示法的变化浮现在脑海(我可能会得到一些讨厌这个):

An alternative is to use different names, if you don't want to have the same names. Some Hungarian-notation variation comes to mind (I might get some hate for this):

//data members
int x_;
int y_;
int width_;
int height_;
//constructor
A::A(int x, int y, int width, int height) :
    x_(x),
    y_(y),
    width_(width),
    height_(height)
{
}

但没有什么不对的第一个建议。

But there's nothing wrong with the first suggestion.