關于有參默認構造函數和初始化列表
#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”嗎?
2020-03-04
一年前的今天? O(∩_∩)O哈哈~? ? ??
2019-03-04