为什么当我添加一个不同的对象(复制构造函数中的参数)时调用复制构造函数?
Why the copy constructor is called when I add a different object which is an argument in copy constructor?
我不明白为什么在将 e 添加到 c 时调用复制构造函数。
struct A {};
struct B {
B() { std :: cout << "B Constructor" << std :: endl; }
B(const A&) { std :: cout << "B Copy" << std :: endl;}
const B operator +(const B& arg);
};
const B B::operator +(const B& arg) {
std :: cout << "+" << std :: endl;
return B();
}
int main() {
B c;
A e;
c + e;
}
它不是被调用的复制构造函数,而是
B(const A&);
复制构造函数始终具有以下签名:
B(const B&);
由于您没有提供,编译器会为您生成一个复制构造函数,但确实没有调用此构造函数:您有一个用于B
的operator+
,它接受const B&
,但另一个操作数的类型为A
。由于第一个提到的构造函数(B(const A&)
)是隐式的,这行得通 - 从名为e
的A
对象实例化一个临时B
,并调用运算符。
若要使示例中的输出更直观,请考虑将构造函数B(const& A)
更改为
B(const A&) { std::cout << "Construct B from An"; }
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 当从函数参数中的临时值调用复制构造函数时
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 使用复制构造函数复制双精度数组
- C 无可行的构造函数复制类型的变量
- 没有可行的构造函数复制类型 'MyString' 的数组元素
- 编译时,复制构造函数/复制分配和正常功能调用优化之间是否存在任何区别
- 如何最小化调用列表构造函数(复制构造函数)的次数?
- C 11矢量构造函数复制与范围
- 我定义了一个非复制构造函数;复制构造函数还会被隐式定义吗
- 可以将构造函数复制为转换运算符
- 将基类指针的构造函数复制到子类
- C++树类:构造函数/复制/内存泄漏
- 如何制作这个在模板构造函数复制中使用类型定义的类型的模板
- 将构造函数复制为模板化的成员函数
- 绕过私有复制构造函数/复制赋值C++
- C++通过构造函数复制对象
- 复制构造函数 - 复制C++中的对象
- 将带unique_ptr的类的构造函数复制到作为成员的抽象类