面试题答案
一键面试功能区别
- 赋值运算符(operator=):主要用于已经存在的对象之间进行赋值操作,会覆盖目标对象已有的数据。
- 拷贝构造函数:用于创建一个新对象,该新对象是另一个已存在对象的副本。
调用时机区别
- 赋值运算符(operator=):当一个已存在的对象被赋予新值时调用。例如:
obj1 = obj2;
,这里obj1
已经存在,执行赋值操作。 - 拷贝构造函数:在以下几种情况调用:
- 用一个对象初始化另一个新对象时,如
ClassType obj2(obj1);
。 - 函数参数按值传递时,会调用拷贝构造函数创建一个形参的副本。
- 函数返回一个对象时,会调用拷贝构造函数创建一个临时对象返回给调用者。
- 用一个对象初始化另一个新对象时,如
参数传递区别
- 赋值运算符(operator=):参数通常是同类型对象的引用,且一般返回对象自身的引用(
*this
),以支持链式赋值。例如:ClassType& operator=(const ClassType& other);
- 拷贝构造函数:参数是同类型对象的引用(一般为
const
引用),构造函数没有返回值。例如:ClassType(const ClassType& other);
示例代码
#include <iostream>
class Example {
private:
int data;
public:
// 构造函数
Example(int value) : data(value) {}
// 拷贝构造函数
Example(const Example& other) : data(other.data) {
std::cout << "Copy constructor called" << std::endl;
}
// 赋值运算符重载
Example& operator=(const Example& other) {
if (this != &other) {
data = other.data;
std::cout << "Assignment operator called" << std::endl;
}
return *this;
}
void printData() const {
std::cout << "Data: " << data << std::endl;
}
};
int main() {
Example obj1(10);
Example obj2(obj1); // 调用拷贝构造函数
Example obj3(20);
obj3 = obj1; // 调用赋值运算符
obj1.printData();
obj2.printData();
obj3.printData();
return 0;
}
在上述代码中,obj2(obj1)
调用了拷贝构造函数创建obj2
,obj3 = obj1
调用了赋值运算符对obj3
进行赋值。