在类声明中,为什么构造函数中的参数不能与私有部分中定义的变量同名?

In Class declaration, why can't the parameters in the constructor have the same name as the variables defined in the private part?

本文关键字:定义 变量 不能 声明 为什么 构造函数 参数      更新时间:2023-10-16

我希望我的问题是清楚的。如果我们有

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

它们可以有相同的名称。但是,当您这样做时,您必须在构造函数体中消除成员与具有相同名称的形参的歧义。