如何使用相同的构造函数参数和字段名称



为什么此代码显示未初始化/垃圾值?当字段名称和构造函数参数不相同时,它会显示正确的值。

#include<bits/stdc++.h>
using namespace std;
class Employee {
public:
Employee(string name,string company,int age)
{
name = name;
company = company;
age = age;
}
string name;
string company;
int age;
void IntroduceYourself()
{
cout<<name<<' '<<company<<' '<<age<<endl;
}
};
int main()
{
Employee employee1= Employee("Saldina","Codebeauty",25);
employee1.IntroduceYourself();
Employee employee2 = Employee("John","Amazon",35);
employee2.IntroduceYourself();
return 0;
}

如果我们在内部作用域中声明一个名称,则该名称将隐藏对外部作用域中所声明名称的使用

作为函数参数的name隐藏作为数据成员的name。你如何判断name中的哪一个应该在这里的哪一边:

name = name
// data_member = parameter ?
// parameter = data_member ?
// parameter = parameter !
// data_member = data_member ?

因此,您的输出IntroduceYourself打印两个空字符串和一个默认初始化的int,因为在构造函数的主体中,您将值重新分配给参数(局部变量(,而数据成员则默认初始化。

有两种常见的方法:

// Not the best practice, but can take place 
Employee(string name,string company,int age) { 
this->name = name;
this->company = company;
this->age = age;
}

和:

Employee(string name, string company, int age) 
: name(name), company(company), age(age) {} // Compiler will sort it out
// Data members
string name;
string company;
int age;

请注意,应该使用成员初始值设定项列表,如第二个示例所示。否则,当"初始化">它们在构造函数的主体中。

最新更新