拷贝构造函数初始化常量的问题
问题:
对象属性里面带常量值的时候,拷贝构造函数就必须使用初始始化列表来给那个常量赋值.比如这样:
Teacher::Teacher(const Teacher& tea):m_iMax(200)
但是,这样赋值导致的结果就是会导致使用这个拷贝构造函数实例化出来没有了另个两个值. m_strName, m_iAge,
而如何使用下面的倒可以把上面丢失的两个值补上来,便这样感觉又把普通构造函数的初始化列表重复了一次. 有没有简单的写法?
Teacher::Teacher(const Teacher& tea):m_strName("dada"),m_iAge(29),m_iMax(200)
//代码如下:
#include <iostream>
#include <string>
using namespace std;
class Teacher
{
public:
Teacher(string name="Linda", int age=19, int m = 100);
Teacher(const Teacher& tea); //tea最后是个变量,可写,可不写.
void setName(string _name);
string getName();
void setGender(string _gender);
string getGender();
void setAge(int _age);
int getAge();
void teach();
int getMax();
private:
string m_strName;
string m_strGender;
int m_iAge;
const int m_iMax; //最多可带学生数;只能使用初始化列表;
};
//使用初始化列表来初始化;
Teacher::Teacher(string name, int age, int m):m_strName(name),m_iAge(age), m_iMax(m)
{
cout << "Teacher::Teacher(string name, int age):m_strName(name),m_iAge(age)" << endl;
}
//Teacher::Teacher(const Teacher& tea):m_strName("dada"),m_iAge(29),m_iMax(200) Teacher::Teacher(const Teacher& tea):m_iMax(200)
{
cout << "Teacher::Teacher(const Teacher& tea)" << endl;
}
void Teacher::setName(string _name)
{
m_strName = _name;
}
string Teacher::getName()
{
return m_strName;
}
void Teacher::setGender(string _gender)
{
m_strGender = _gender;
}
string Teacher::getGender()
{
return m_strGender;
}
void Teacher::setAge(int _age)
{
m_iAge = _age;
}
int Teacher::getAge()
{
return m_iAge;
}
void Teacher::teach()
{
cout << "现在上课..." << endl;
}
int Teacher::getMax()
{
return m_iMax;
}
int main(void)
{
Teacher t1;
cout << "T1: " << t1.getName() << ", " << t1.getAge() << ", stu: " << t1.getMax() << endl;
Teacher t3 = t1;
cout << "T3: " << t3.getName() << ", " << t3.getAge() << ", stu: " << t3.getMax() << endl;
Teacher t4(t1);
cout << "T4: " << t4.getName() << ", " << t4.getAge() << ", stu: " << t4.getMax() << endl;
}
运行结果;
Teacher::Teacher(string name, int age):m_strName(name),m_iAge(age)
T1: Linda, 19, stu: 100
Teacher::Teacher(const Teacher& tea)
T3: , 0, stu: 200
Teacher::Teacher(const Teacher& tea)
T4: , 1073741824, stu: 200