當我試圖多載<<運算子時,我無法讓下面的代碼編譯。誰能指出哪里出了問題?
#include <iostream>
std::ostream& operator<<(std::ostream& i, int n)
{
return i。
}
int main()
{
std::cout << 5 << std::endl;
std::cin.get()。
return 0;
}
uj5u.com熱心網友回復:
在C 標準庫中已經為int型別的物件定義了運算子<<
。basic_ostream<charT, traits>& operator< <(int n)。
所以這個陳述句中對運算子的呼叫
std::cout << 5 << std::endl;
是模棱兩可的,因為由于引數的依賴性查找,找到了標準運算子。
為了解除ADL的作用,你可以寫一些例如下面這樣的東西,用兩個引數明確地呼叫運算子
std::ostream& operator<<(std::ostream& i, int n)
{
return i.operator << ( n );
}
int main()
{
operator <<( std::cout, 5 ) << std::endl;
std::cin.get()。
return 0;
}
程式輸出是
5
盡管這并不是很有意義。:)
uj5u.com熱心網友回復:
因為不止一個運算子"<< "匹配這些運算子。
std::ostream& operator<<(std::ostream& i, int n)已被定義。
TypeA a = (TypeB)operand1 operator (TypeC)operand2
將operator看作是一個函式,它翻譯成這個函式:
TypeA operator(TypeB operand1, TypeC operand2)
定義兩次func將導致編譯錯誤。
要多載<<,請嘗試:
std::ostream& operator<<(std::ostream& i, OtherType n)
或者
AnyType operator<<(AnyType i, AnyType n)/code>
只是不要重復。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/314150.html
標籤:
