C++复制控制
- C/C++ code
class Person{protected: string name; char sex; int age;public: Person(void) { cout<<"In Person(void)"<<endl; } ~Person(void) { cout<<"In ~Person(void)"<<endl; } Person(string name, char sex, int age) { cout<<"In Person(string name, char sex, int age)"<<endl; this->name = name; this->sex = sex; this->age = age; } virtual void printInfo(void) { cout<<"name:"<<name<<endl<<"age:"<<age<<endl; cout<<"sex:"; if(sex == 0) { cout<<"Male"; }else { cout<<"Female"; } cout<<endl; }};class Employee:public Person{private: int emp_num; int salary; string job; public: Employee(const Employee &e) { this->age = e.age + 10; this->emp_num = this->emp_num + 2; this->job = e.job; this->name = e.name; this->salary = e.salary; this->sex = e.sex; cout << "In Employee(const Employee &e)"<<endl; } Employee(void) { cout<<"In Employee(void)"<<endl; } ~Employee(void) { cout<<"In ~Employee"<<endl; } Employee(string name, char sex, int age, int emp_num, int salary, string job):Person(name, sex, age) { cout<<"In Employee(string name, char sex, int age, int emp_num, int salary, string job)"<<endl; this->emp_num = emp_num; this->salary = salary; this->job = job; } void operator=(Employee e) { this->age = e.age + 3; this->emp_num = this->emp_num + 1; this->job = e.job; this->name = e.name; this->salary = e.salary; this->sex = e.sex; cout << "In Employee ="<<endl; } void printInfo(void) { cout<<"name:"<<name<<endl<<"age:"<<age<<endl; cout<<"sex:"; if(sex == 0) { cout<<"Male"; }else { cout<<"Female"; } cout<<endl<<"emp_num:"<<emp_num<<endl<<"salary:"<<salary<<endl<<"job:"<<job<<endl; }};int _tmain(int argc, _TCHAR* argv[]){ Employee e_1("zhb", 0, 25, 20, 5000, "enigeer"); Employee e_2("pf", 0, 25, 1000, 2000, "unknown"); e_1 = e_2; system("pause"); return 0;}e_1 = e_2;这部分为什么会先后调用了复制构造函数和赋值运算符?e_1已经初始化过了,这里不是应该只调用赋值运算么?谢谢解答。
[解决办法]
void operator=(Employee e);
这种传参是按指传递,所以传参的时候会调用 复制构造函数。
改为
void operator=(Employee& e)就不会了。
而且一般都使用引用。