参数构造函数的命名 [英] Parameters Naming for Constructor

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

问题描述

在Java中,通常,我可以使我的构造函数的参数与成员变量同名。

In Java, usually, I can have my constructor's parameters same name as member variables.

public A(int x)
{
    this.x = x;
}

private int x;

在C ++中,我不能。通常,我必须这样做。

In C++, I can't. Usually, I have to do it this way.

public:
    A(int x_) : x(x_) 
    {
    }

private:
    int x;

有更好的方法吗?因为构造函数的参数名看起来很丑陋,当IDE IntelliSense弹出构造函数参数窗口。

Is there any better way? As the constructor parameters name look ugly, when IDE IntelliSense pop up the constructor parameters windows.

推荐答案

您想要:

struct A {
  int x;
  A(int x) : x(x) {
    foo(this->x);
    // if you want the member instead of the parameter here
  }
};



< c $ c>),我为非公开成员做。如果在这个例子中 x 是public的,我会这样做,如果我认为ctor的参数更容易读,看看重命名ctor的参数。

Though I also commonly use stylistic names for members (e.g. _x), I do it for non-public members. If x is public as in this example, I would do it like this, and look at renaming the ctor's parameter if I thought it would be more readable.

编辑:由于人们似乎被侧线,我会在 _x 中澄清。该标准保留一些标识符名称:

Since people seem to be getting sidetracked, I'll clarify on _x. The standard reserves some identifier names:


  • 任何名称空间中都有两个相邻的下划线


  • 任何在全局范围内带有前导下划线的名称

由于成员范围限于类,它们不属于第三类。也就是说,这将是很高兴不继续侧线。 :)如果你愿意,随时对C ++中的保留标识符提出一个问题,并在评论中发布一个链接。

Since members are scoped to the class, they do not fall in the third category. That said, it would be nice to not continue getting sidetracked. :) Feel free to ask a question about reserved identifiers in C++ and post a link to it in the comments if you want.

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

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