C++ 拷贝构造函数调用时机
#include <iostream>
// 一个简单的类,用于演示
class Widget {
public:
// 1. 默认构造函数
Widget() {
std::cout << "默认构造函数被调用 (Default Constructor called)." << std::endl;
}
// 2. 拷贝构造函数
// 它接收一个同类对象的常引用作为参数
Widget(const Widget& other) {
std::cout << "拷贝构造函数被调用 (Copy Constructor called)." << std::endl;
}
// 3. 拷贝赋值运算符
// 注意:这不是构造函数,它在对象已经被创建后才被调用
Widget& operator=(const Widget& other) {
std::cout << "拷贝赋值运算符被调用 (Copy Assignment Operator called)." << std::endl;
// 避免自我赋值