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

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

问题描述

可能的重复:
C++ 中的成员与方法参数访问

我有一个包含一些成员的类,例如 xywidthheight.在它的构造函数中,我不会这样做:

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++ xywidthheight 编译时,这真的没有意义> 变成奇怪的值(例如 -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.

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

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