【发布时间】:2020-09-20 05:59:09
【问题描述】:
我正在阅读一本 C++ 书籍,上面写着:
template<class T>
T max(const T& a, const T& b)
{
return a>b?a:b;
}
int main()
{
int n1= 7,n2= 5;
Complex c1(2.0, 1.0), c2(0.0, 1.0);
cout << max(n1, n2) << endl;
cout << max(c1, c2) << endl;
//Compilation Error, can't compile max<complex> since there is no operator >() for complex numebrs.
return 0;
}
这是什么意思,我在哪里使用了() 运算符来表示复数,它的一般工作是什么? (尽管我读到了 () 运算符,但我并不理解它背后的全部想法)
Complex 是一个有 2 个字段的类,一个(两个双精度数)一个用于实数,一个用于虚数,此外它还有 > 运算符
【问题讨论】:
-
如果没有看到
Complex的定义,很难回答这个问题。 -
编辑了我的问题
-
您的代码是否使用
using namespace std;,因为有一个名为max的std 函数,它可能会与您的版本混淆。基本上需要看所有代码,否则只是猜测, -
@Vlad 你的回答是对的,请再次发表,他写的是 'operator >()' 而不是 'operator ()' 我看错了!
标签: c++ templates operator-overloading operators