[英]Ambiguous overload for ‘operator>>’ in ‘std::cin >>'
[英]C++ Ambiguous over for 'operator>>' in 'std::cin >>'
我正在處理的作業有問題。 我們正在編寫一個在其自己的名稱空間中定義的復數類。 除了istream和ostream的超載之外,我一切正常。 讓我發布一些代碼:
namespace maths {
class complex_number{
public:
// lots of functions and two variables
friend std::istream& operator >>(std::istream &in, maths::complex_number &input);
}
}
std::istream& operator >>(std::istream &in, maths::complex_number &input)
{
std::cout << "Please enter the real part of the number > ";
in >> input.a;
std::cout << "Please enter the imaginary part of the number > ";
in >> input.b;
return in;
}
int main(int argc, char **argv)
{
maths::complex_number b;
std::cin >> b;
return 0;
}
我收到的錯誤如下:
com.cpp: In function ‘int main(int, char**)’:
com.cpp:159:16: error: ambiguous overload for ‘operator>>’ in ‘std::cin >> b’
com.cpp:159:16: note: candidates are:
com.cpp:131:15: note: std::istream& operator>>(std::istream&, maths::complex_number&)
com.cpp:37:26: note: std::istream& maths::operator>>(std::istream&, maths::complex_number&)
我花了一些時間瀏覽這里的論壇,偶然發現了有關名稱隱藏的答案,但似乎無法使其與我的代碼一起使用。 任何幫助是極大的贊賞!
之所以模棱兩可,是因為您有兩個單獨的功能。 其中一個駐留在maths
命名空間中,並由該類內一個標記為friend
聲明。 可以通過“依賴於參數的查找”找到該對象。 您還可以在名稱空間之外具有完整的定義。 這兩個都是同等有效的。
首先,它不訪問該類的任何私有成員,因此不需要friend
聲明。 只是不要讓它成為朋友,因為那只會損害封裝。
其次,我建議將定義移入maths
命名空間,因為它與正在操作的類一起屬於該命名空間。 如前所述,ADL仍會找到它,因為第二個參數是該名稱空間中的類型,因此將搜索名稱空間並找到重載。
總而言之,您應該得到以下結果:
namespace maths {
class complex_number{
public:
// lots of functions and two variables
};
std::istream& operator >>(std::istream &in, maths::complex_number &input)
{
std::cout << "Please enter the real part of the number > ";
in >> input.a;
std::cout << "Please enter the imaginary part of the number > ";
in >> input.b;
return in;
}
}
int main(int argc, char **argv)
{
maths::complex_number b;
std::cin >> b; //operator>> found by ADL
return 0;
}
最后一點是過載本身。 輸入實際上不應該提示輸入,而應該閱讀它們。 這樣,您可以將其與鍵盤,文件或任何其他std::istream
派生類一起使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.