我可以为字段和构造函数参数使用相同的名称吗? [英] Can I use identical names for fields and constructor parameters?

查看:156
本文介绍了我可以为字段和构造函数参数使用相同的名称吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  
class C {
T a;
public:
C(T a):a(a){;}
};

是否合法?

方案

是的,它是合法的,适用于所有平台。
它将正确地初始化您的成员变量a,传递的值a。



它被一些更干净的认为是不同的,但不是全部。我个人实际上使用它很多:)



具有相同变量名称的初始化列表起作用,因为初始化列表中初始化项的语法如下:



< member>(< value>)



您可以通过创建一个简单的程序这样做:(它不会编译)

  A类
{

A int a)
:a(5)//< ---尝试将非成员变量初始化为5
{
}
};

你将得到一个类似于以下的编译错误:A没有名为'a'的字段。 / p>




在旁注:



strong>可能不希望使用与参数名称相同的成员名称是您将更容易出现以下情况:

  class A 
{

A(int myVarriable)
:myVariable(myVariable)//< --- Bug,在参数名称中有一个错字, myVariable将永远不会被正确初始化
{
}
int myVariable;
};






在旁注(2) p>

可能希望将同一成员名称用作参数名称的一个原因是您不太容易遇到以下情况:

  class A 
{

A(int myVariable_)
{
/ /< - 使用_myVariable执行某些操作,oops _myVariable尚未初始化
...
_myVariable = myVariable_;
}
int _myVariable;
};

这也可能发生在大型初始化列表中,并且在初始化列表中初始化之前使用_myVariable。



class C {
  T a;
public:
  C(T a): a(a) {;}
};

Is it legal?

解决方案

Yes it is legal and works on all platforms. It will correctly initialize your member variable a, to the passed in value a.

It is considered by some more clean to name them differently though, but not all. I personally actually use it a lot :)

Initialization lists with the same variable name works because the syntax of an initialization item in an initialization list is as follows:

<member>(<value>)

You can verify what I wrote above by creating a simple program that does this: (It will not compile)

class  A
{

   A(int a)
   : a(5)//<--- try to initialize a non member variable to 5
   {
   }
};

You will get a compiling error something like: A does not have a field named 'a'.


On a side note:

One reason why you may not want to use the same member name as parameter name is that you would be more prone to the following:

class  A
{

   A(int myVarriable)
   : myVariable(myVariable)//<--- Bug, there was a typo in the parameter name, myVariable will never be initialized properly
   {
   }
   int myVariable;
};


On a side note(2):

One reason why you may want to use the same member name as parameter name is that you would be less prone to the following:

class  A
{

   A(int myVariable_)
   {
     //<-- do something with _myVariable, oops _myVariable wasn't initialized yet
     ...
     _myVariable = myVariable_;
   }
   int _myVariable;
};

This could also happen with large initialization lists and you use _myVariable before initializing it in the initialization list.

这篇关于我可以为字段和构造函数参数使用相同的名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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