开发者

Parameters Naming for Constructor

开发者 https://www.devze.com 2022-12-12 00:12 出处:网络
In Java, usually, I can have my constructor\'s parameters same name as member variables. public A(int x)

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;

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

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

private:
    int x;

Is there any better 开发者_Go百科way? As the constructor parameters name look ugly, when IDE IntelliSense pop up the constructor parameters windows.


In C++, you can, if you want:

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

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.

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

  • any name with two adjacent underscores, in any namespace
  • any name with a leading underscore followed by an uppercase letter, in any namespace
  • any name with a leading underscore at global scope

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.


You can actually do this the Java way in C++:

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

But then it's also possible to just say x(x):

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


C++ is smart enough to figure out which x you mean, you can write:

class A {
  int x;
  A( int x ) : x(x) {};
};


Google style is to make the members have the trailing underscore:

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

private:
  int x_;

Much prettier.


I don't think this is possible. However, I would highly recommend using a consistent naming convention for member variables to differentiate them from parameters and local variables.

In my company we usually denote member variables with an 'm' prefix, e.g.:

int mMyMemberVariable;

or

int m_MyMemberVariable;

This is just an example of a style - consistency is the key.


One way (and some may argue that the this is the C++ way) would be to prefix your class's fields with m_ to disambiguate between the field and the constructor argument name.

0

精彩评论

暂无评论...
验证码 换一张
取 消