![](/img/trans.png)
[英]Why is the copy constructor called on a function argument when the argument is passed by reference?
[英]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 A\n"; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.