【发布时间】:2021-09-21 07:33:53
【问题描述】:
为什么这段代码显示未初始化/垃圾值?当字段名称和构造函数参数不相同时,它显示正确的值。
#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;在做什么?编译器应该如何区分数据成员名和函数参数名? -
设置的变量是类变量还是局部变量是模棱两可的。如果要使用相同的字段名称,请在构造函数中使用 this 关键字,例如this->name = name;
-
这个关键字的实际作用是什么?它是否引用类变量?@AjitVaze
-
@Roman 它指的是你正在使用的对象。
标签: c++ constructor