[英]Ambiguous Overload For operator “<<”
我正在學習C ++中的運算符重載,我想知道以下代碼的輸出
#include<iostream>
using namespace std;
class xyz
{
public:
int i;
friend ostream & operator<<( ostream & Out , int);
};
ostream & operator<<(ostream & out , int i)
{
cout<<10+i<<endl;
}
int main()
{
xyz A;
A.i=10;
cout<<10;
}
我有兩個錯誤
錯誤:'operator <<'的模棱兩可的重載(操作數類型為'std :: ostream {aka std :: basic_ostream}'和'int')cout << 10 + i;
錯誤:'operator <<'的模棱兩可的重載(操作數類型為'std :: ostream {aka std :: basic_ostream}'和'int')cout << 10;
誰能解釋這個問題是什么?
我想知道如果我重載“ <<”運算符以僅使用一個參數int(obvious)打印int,而我只想單獨打印一個數字,例如上述代碼“ cout << 10” int,會發生什么。 因此,當我嘗試僅打印任何整數時,編譯器將如何決定應調用哪個函數。
所以很明顯,問題是您已經編寫了ostream & operator<<(ostream & out , int i)
。 但是很明顯,您要寫的是這樣的
ostream& operator<<(ostream& out, const xyz& a) // overload for xyz not int
{
out<<a.i<<endl; // use out not cout
return out; // and don't forget to return out as well
}
和這個
int main()
{
xyz A;
A.i=10;
cout<<A<<endl; // output A not 10
}
// this include brings std::ostream& operator<<(std::ostream&, int)
// into scope and therefore you cannot define your own later
#include<iostream>
using namespace std;
class xyz
{
public:
int i;
// needs body
friend ostream & operator<<( ostream & Out , int)
{
return Out;
}
};
/* cant have this after including ostream
ostream & operator<<(ostream & out , int i)
{
cout<<10+i<<endl;
}
*/
int main()
{
xyz A;
A.i=10;
cout<<10;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.