为什么当我在复制构造函数中添加一个作为参数的不同对象时调用复制构造函数?
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&);
因为你没有提供一个,编译器为你生成了一个复制构造函数,但是这个确实没有被调用:你有一个 operator+
for B
,它接受一个 const B&
,但另一个操作数的类型是 A
。由于首先提到的构造函数 (B(const A&)
) 是 implicit,因此可以解决 - 从名为 [=20] 的 A
对象实例化临时 B
=],并调用运算符。
为了使示例中的输出更直观,请考虑将构造函数 B(const& A)
更改为
B(const A&) { std::cout << "Construct B from A\n"; }
我不明白为什么在将 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&);
因为你没有提供一个,编译器为你生成了一个复制构造函数,但是这个确实没有被调用:你有一个 operator+
for B
,它接受一个 const B&
,但另一个操作数的类型是 A
。由于首先提到的构造函数 (B(const A&)
) 是 implicit,因此可以解决 - 从名为 [=20] 的 A
对象实例化临时 B
=],并调用运算符。
为了使示例中的输出更直观,请考虑将构造函数 B(const& A)
更改为
B(const A&) { std::cout << "Construct B from A\n"; }