我现在正在关注C ++课程,尝试从这里编译示例:Ira Pohl’s C++ by Dissection同时使用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;
}
答案 0 :(得分:4)
greater
函数出现在导入的std
namespace以及源文件中,因此编译器无法决定应该使用哪一个。
也许这不是Borland C ++ 5.0的情况,所以代码编译得很好。这是一个很好的例子,为什么using namespace std
通常是一个坏主意。
您可能会尝试删除该声明,并在需要时手动添加显式std::
前缀(编译器会告诉您)。