我正在尝试实现一个复制构造函数和一个重载的赋值构造函数 . 我有一个有三个数据成员的Employee类 . 1-name 2-title 3-salary .
Employee::Employee(const Employee &emp)
{
name = emp.name;
title = emp.title;
salary = emp.salary;
cout << "\nOverloaded copy constructor called\n";
}
Employee Employee::operator = (const Employee &emp) //Overloading the assignment operator.
{
name = emp.name;
title = emp.title;
salary = emp.salary;
cout << "\nOverloaded assignment operator called\n";
return emp; //Or return *this.
}
这是我不明白的:
1-我没有't got to the 1712222 pointer. Should my overloaded assignment operator return this or the emp object. Because it seems to me that that object in the parameter is the right hand object at the assignment. So shouldn' t我用 this返回左手对象(如果这是*将要做什么)?
2-在main函数中,我尝试先调用赋值运算符,然后调用复制构造函数 . 所以我期待着我会看到我输出的cout语句:
重载的拷贝构造函数被调用
调用重载赋值运算符
重载的拷贝构造函数被调用
重载的拷贝构造函数被调用
为什么会这样?
3 - 我必须用const传递对象吗?我正在学习的这本书没有 .
在我写的主要内容中
Employee x;
x = another;
Employee y = x;
"another"只是我之前在代码中初始化的一个(命名不佳的)Employee对象 .
所以不应该是第一个分配输出
"Overloaded assignment operator called"和第二个作业(根据我的理解不是作业而是副本)输出"Overloaded copy constructor called"