构造函数参数初始化列表与构造函数中使用赋值运算符的工作方式不同吗?
我有以下代码:
class Person1
{
public:
int age;
string name;
double weight;
double height;
Person1();
Person1(int age, string name, double weight, double height);
};
Person1::Person1()
{
}
Person1::Person1(int age, string name, double weight, double height)
//: m_age{age}, m_name{name}, m_weight{weight}, m_height{height}
{
// this->age = age;
// this->name = name;
// this->height = height;
// this->weight = weight;
age = age;
name = name;
height = height;
weight = weight;
}
void ModifyPerson1(Person1 person1)
{
person1.name = "Jerry";
cout << person1.age << " " << person1.name << " " << person1.weight << " " << person1.height << endl;
}
int main()
{
Person1 person1(15,"Tom",140,5);
cout << person1.age << " " << person1.name << " " << person1.weight << " " << person1.height << endl;
ModifyPerson1(person1);
cout << "Name after modification : " << person1.name << endl;
return 0;
}
以上代码的OP是:
-272632464 6.95313e-310 2.12202e-314
-272632464 Jerry 6.95313e-310 2.12202e-314
修改后的名称:
程序以退出代码结束:0
如果我使用初始化列表或者这个 - >构造函数的运算符,输出是预期的:
15 Tom 140 5
15 Jerry 140 5
修改后的名称:Tom
程序以退出代码结束:0
我严重无法理解为什么行为不同。