成员名和构造函数参数名之间的冲突 [英] Conflicts between member names and constructor argument names

查看:142
本文介绍了成员名和构造函数参数名之间的冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能的重复:

C ++中的成员与方法参数访问





x , y code>和 height 。在其构造函数中,我不会这样做:

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 y width / code>变成奇怪的值(例如 -1405737648 )。

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

这些命名冲突?

推荐答案

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

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.

这篇关于成员名和构造函数参数名之间的冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆