gpt4 book ai didi

c++ - C++ 中不明确的函数重载

转载 作者:行者123 更新时间:2023-11-27 22:48:38 25 4
gpt4 key购买 nike

我现在正在学习 C++ coursera 类(class),试图从这里编译示例:Ira Pohl’s C++ by Dissection使用 g++ 和 intel 的 c++ 编译器。

两个编译器都有一些错误,就像每次调用 greater 时这样:

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 namespace 中以及源文件,因此编译器无法决定应该使用哪一个。

也许 Borland C++ 5.0 不是这种情况,所以当时的代码编译得很好。这是一个很好的例子,为什么 using namespace std 通常不是一个好主意。

您可能会尝试删除该声明并在需要的地方手动添加显式 std:: 前缀(编译器会告诉您)。

关于c++ - C++ 中不明确的函数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40195984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com