我可以对字段和构造函数参数使用相同的名称吗?

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

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

问题描述


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

合法吗?

推荐答案

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

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:

<成员>(<值>)

你可以通过创建一个简单的程序来验证我上面写的内容:(它不会编译)

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
   {
   }
};

您将收到类似如下的编译错误:A 没有名为 'a' 的字段.

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

附注:

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

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;
};

<小时>

附注(2):


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;
};

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

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

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

本文标题为:我可以对字段和构造函数参数使用相同的名称吗?

基础教程推荐