为什么当我添加一个不同的对象(复制构造函数中的参数)时调用复制构造函数?

Why the copy constructor is called when I add a different object which is an argument in copy constructor?

本文关键字:构造函数 复制 对象 参数 调用 添加 为什么 一个      更新时间:2023-10-16

我不明白为什么在将 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&);

由于您没有提供,编译器会为您生成一个复制构造函数,但确实没有调用此构造函数:您有一个用于Boperator+,它接受const B&,但另一个操作数的类型为A。由于第一个提到的构造函数(B(const A&))是隐式的,这行得通 - 从名为eA对象实例化一个临时B,并调用运算符。

若要使示例中的输出更直观,请考虑将构造函数B(const& A)更改为

B(const A&) { std::cout << "Construct B from An"; }