[英]Ambiguous function overload in C++
我現在正在遵循C ++課程,試圖從此處編譯示例: Ira Pohl的Dissection C ++和g ++和intel的c ++編譯器。
兩種編譯器都出現了一些錯誤,例如每次調用更大的代碼時都這樣:
rational.cpp(69): error: "greater" is ambiguous
<< greater(i, j);
^
/***************************************************************
* C++ by Dissection By Ira Pohl Addison Wesley
* Chapter 5 Ctors, Dtors, Conversion, and Operator Overloading
* Compiled with Borland C++ Builder Version 5.0 Summer 2001
******************************************************************/
//Overloading functions
#include <iostream>
using namespace std;
// Overloading functions
class rational {
public:
rational(int n = 0) : a(n), q(1) { }
rational(int i, int j) : a(i), q(j) { }
rational(double r) : a(static_cast<long>
(r * BIG)), q(BIG) { }
void print() const { cout << a << " / " << q; }
operator double()
{ return static_cast<double>(a) / q; }
friend ostream& operator<<(ostream& out, const rational& x);
friend istream& operator>>(istream& in, rational& x);
friend bool operator>(rational w, rational z);
private:
long a, q;
enum { BIG = 100 };
};
ostream& operator<<(ostream& out, const rational& x)
{
return (out << x.a << " / " << x.q << '\t');
}
istream& operator>>(istream& in, rational& x)
{
return (in >> x.a >> x.q);
}
bool operator>(rational w, rational z)
{
return (static_cast<double>(w.a) / w.q > static_cast<double>(z.a) / z.q);
}
inline int greater(int i, int j)
{ return (i > j ? i : j); }
inline double greater(double x, double y)
{ return (x > y ? x : y); }
inline rational greater(rational w, rational z)
{ return (w > z ? w : z); }
int main()
{
int i = 10, j = 5;
float x = 7.0;
double y = 14.5;
rational w(10), z(3.5), zmax;
cout << "\ngreater(" << i << ", " << j << ") = "
<< greater(i, j);
cout << "\ngreater(" << x << ", " << y << ") = "
<< greater(x, y);
cout << "\ngreater(" << i << ", ";
z.print();
cout << ") = "
<< greater(static_cast<rational>(i), z);
zmax = greater(w, z);
cout << "\ngreater(";
w.print();
cout << ", ";
z.print();
cout << ") = ";
zmax.print();
cout << endl;
}
greater
功能存在於導入的std
名稱空間以及源文件中,因此編譯器無法確定應使用哪個功能。
Borland C ++ 5.0可能不是這種情況,因此當時的代碼可以很好地編譯。 這是一個很好的示例,為什么using namespace std
通常不是一個好主意。
您可以嘗試刪除該聲明,然后在需要的地方手動添加一個顯式的std::
前綴(編譯器會告訴您)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.