Naming convention for params of ctors and setters

2019-02-13 12:42发布

For those of you who name you member variables with no special notation like m_foo or foo_, how do you name parameters to your ctors and setters?

Some options I've tried so far...

Obj(int foo) : foo(foo) { }
void set_foo(int foo) { this->foo = foo; }

Obj(int _foo) : foo(_foo) { }
void set_foo(int _foo) { foo = _foo; }

Obj(int a_foo) : foo(a_foo) { } // a for "argument"
void set_foo(int a_foo) { foo = a_foo; }

Obj(int init_foo) : foo(init_foo) { }
void set_foo(int new_foo) { foo = new_foo; }

12条回答
【Aperson】
2楼-- · 2019-02-13 12:45

I always go for a Param or Arg suffix but only when disambiguation is necessary.

Obj(int fooArg) : foo(fooArg)
查看更多
一夜七次
3楼-- · 2019-02-13 12:47

Number two has problems as a convention, although in your case it could be harmless. A name that has a leading underscore followed by an uppercase character is reserved for the implementation, and all names with leading underscores are reserved in a global context. If you never have class members beginning with uppercase letters (I don't), you're safe with the convention as shown (using _foo only as a function argument), but I dislike naming conventions that skirt anywhere near the limits.

查看更多
男人必须洒脱
4楼-- · 2019-02-13 12:49

I'm going with

Obj(int foo) : mFoo(foo) { }
void setFoo(int foo) { mFoo = foo; }

in my programs. For copy constructors and operator=, i tend to call it

Obj(Obj const& that):mFoo(that.mFoo) { }

For operators, i'm going with

Obj operator+(Obj const& lhs, Obj const& rhs) { ... }

Because those are the left hand side and the right hand side of it.

查看更多
小情绪 Triste *
5楼-- · 2019-02-13 12:51

I follow the Google C++ Style Guide

Variable names are all lowercase, with underscores between words. Class member variables have trailing underscores. For instance: my_exciting_local_variable, my_exciting_member_variable_.

查看更多
【Aperson】
6楼-- · 2019-02-13 12:54

For classes:

Obj(int foo) : _foo(foo) {};

For structs:

obj_t(int foo_) : foo(foo_) {};

Setter:

Obj.setFoo(int foo) { _foo = foo; }

I'm with litb on the use of lhs and rhs for operator calls.

I use camelCase for class member functions, and names_with_underscores for struct fields and methods.

查看更多
Animai°情兽
7楼-- · 2019-02-13 12:56

I always do this:

Obj(int foo) : foo(foo) {}

I used to play games with appending funny symbols until one time I got hit by this:

Obj(Bar& b) : b_(b_) {}

Can you see the mistake? (Yes, b_ is a private member reference variable). It compiled without a warning. Cost me 3 days of debugging (I was a green programmer then).

Now I always use the same name to avoid typos (and subsequent crashes) like that. There is no ambiguity inside the initialization list. This part of the language was designed just for this case, so take advantage of it.

查看更多
登录 后发表回答