关于有参默认构造函数和初始化列表
#include<iostream>
#include<string>
using namespace std;
class Teacher{
public:
Teacher(string m_strName = "Jim",int age = 1);
void setName(string name);
string getName();
void setAge(int age);
int getAge();
private:
string m_strName;
int m_iAge;
};
Teacher::Teacher(string name,int age):m_strName("anllla"),m_iAge(age)
{
cout << "the function is executed!" << endl;
}
void Teacher::setName(string name)
{
m_strName = name;
}
string Teacher::getName()
{
return m_strName;
}
void Teacher::setAge(int age)
{
m_iAge = age;
}
int Teacher::getAge()
{
return m_iAge;
}
int main()
{
Teacher t1;
cout << t1.getName() << "," << t1.getAge() << endl;
cout<<"after modifying:" << endl;
t1.setName("Lily");
t1.setAge(2);
cout << t1.getName() << "," << t1.getAge() << endl;
return 0;
}
老师,我为了验证初始化列表是先于构造函数执行的,在初始化列表中又给了一个m_strName一个“anllla”的名字,但是第一次输出的结果还是“anlla”
我的疑问是,当用初始化列表初始化了一个“anlla”之后,之后不是接着执行构造函数吗?而构造函数中默认赋值是“Jim”,所以第一次输出m_str_Name时不应该输出后来覆盖的那个“Jim”吗?