我正在尝试实现一个复制构造函数和一个重载的赋值构造函数 . 我有一个有三个数据成员的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"
4 回答
赋值运算符通常实现为
请注意返回类型的差异作为参考 . 您可能会发现此问题/答案有用Why must the copy assignment operator return a reference/const reference? . 如果没有看到您在
main()
函数中引用的代码,我们只会猜测您的代码中发生了什么 .你应该返回
*this
.另请注意,首先应检查自我分配并返回引用:
Here you can find how to write assignment operator.
请从
main()
插入此代码,以便我们为您提供更多信息 .编辑:让我们复制构造函数为你做一切
更多关于赋值运算符中的异常安全和自赋值处理:GotW 59和GotW 23