[英]Should a constructor ever be called on assignment?
VS2015中以下代碼的輸出是“構造函數”。
由於缺少賦值運算符,它不應該無法編譯嗎?
struct A { };
struct B {
B(){}
B(const A& a) {
cout << "constructor" << endl;
}
//B& operator=(const A& a) {
// cout << "assignment operator" << endl;
// return *this;
//}
};
int main() {
A a;
B b;
b = a;
return 0;
}
是的,當有轉換時,就像在您的測試用例中一樣。
你有效地打電話了
b = B(a);
因為B
的賦值運算符B& operator=(B const&)
是隱式聲明的,所以在重載解析期間會找到它。 因為您的分配只是一次轉換而不是匹配(並且這恰好是允許發生的轉換次數),所以它將a
轉換為B
,然后將新的臨時B
分配給b
。
讓我們考慮一個類似的例子。
double a;
int b=5;
a=b;
你可以分配給double
的唯一的東西是另一個double
。 但是, int
可以轉換為double
。
同樣在這里, A
可以轉換為B
,因為存在這樣的構造函數。 這就是發生的事情。
你的代碼有從A
到B
隱式轉換, b = a
編譯為b = B(a);
。 如果要將其檢測為錯誤,可以使用explicit
說明符 :
struct B {
B(){}
explicit B(const A& a) {
std::cout << "constructor" << std::endl;
}
};
然后你應該得到錯誤,例如ideone.com生成的錯誤 :
prog.cpp: In function 'int main()':
prog.cpp:20:7: error: no match for 'operator=' (operand types are 'B' and 'A')
b = a;
^
prog.cpp:5:8: note: candidate: B& B::operator=(const B&)
struct B {
^
prog.cpp:5:8: note: no known conversion for argument 1 from 'A' to 'const B&'
prog.cpp:5:8: note: candidate: B& B::operator=(B&&)
prog.cpp:5:8: note: no known conversion for argument 1 from 'A' to 'B&&'
之后,永遠不會隱式調用構造函數,如果要調用它,則必須明確地編寫它: b = B(a);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.