在类声明中,为什么构造函数中的参数不能与私有部分中定义的变量同名?
In Class declaration, why can't the parameters in the constructor have the same name as the variables defined in the private part?
我希望我的问题是清楚的。如果我们有
Class A
{
public:
A(); //default constructor
A(int new_a, string new_b);
private:
int a;string b;
};
(对不起,我是堆栈溢出的新手,我的格式可能很糟糕。)
"new_a"answers"new_b"不就是私处的a和b吗?为什么我们要给他们取不同的名字?
谢谢你的回答!
你可以这样声明构造函数
Class A
{
public:
A(); //default constructor
A( int a, string b);
private:
int a;string b;
};
根据c++标准
在函数声明中,或在除函数定义的声明符(8.4),形参的名称(if(提供)具有函数原型作用域,该作用域在结束时终止最近的封闭函数声明符
因此成员函数形参可以与类的私有数据成员具有相同的名称。你也可以这样定义构造函数
A::A( int a, string b) : a( a ), b( b ) {}
或
A::A( int a, string b){ A::a = a; A::b = b; }
或
A::A( int a, string b){ this->a = a; this->b = b; }
它们可以有相同的名称。但是,当您这样做时,您必须在构造函数体中消除成员与具有相同名称的形参的歧义。
相关文章:
- 在头文件中定义变量不会出错
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- 在命名空间中定义变量
- 是否可以在C++中基于程序集输出(.dll或.exe)定义变量
- 用不同类型重新定义变量
- 具有全局定义变量的递归比没有全局定义变量的递归函数获得更多的堆栈.为什么?(跳入C++)
- 定义变量类型
- 在命名空间中定义变量,但在测试中获取空值
- cmake没有定义变量
- C 中的继承:在亲子类中定义变量
- 在同一函数中定义变量及其静态等效项
- 如何在 Tensorflow C++ 中定义变量的自定义有状态 Op 保存值
- 如何将 int 和 int* 传递到函数中以定义变量
- 在定义变量时调用类函数
- 定义变量与模板
- 定义变量类型
- 为什么您可以在 switch 语句中的"默认"下定义变量,而不能在"case"下定义变量
- C 如何基于另一个变量和某些算术定义变量的值
- C 可以指向具有定义变量的函数
- C 定义变量设置值