【问题标题】:C++, () operator overloading, what's its jobC++,()运算符重载,它的工作是什么
【发布时间】: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


【解决方案1】:

问题是您的Complex 类没有定义可用于max() 函数中比较两个const Complex 对象的operator &gt;

检查operator &gt;是否被声明为成员函数,该函数是否被声明为const函数,或其参数是否为const引用。

运算符应声明为成员函数,如下所示:

bool operator >( const Complex & ) const;

或者,如果它被声明为非成员函数(例如 friend 函数),那么它应该这样声明:

bool operator >( const Complex &, const Complex & );

【讨论】:

  • 它有,阅读错误信息“can't compile max because there is no operator ()”是说它没有 () 运算符根据作者
  • @clark_smith 我认为如果将运算符声明为成员函数,那么它就不是常量成员函数。:)
  • @clark_smith 再次仔细阅读了作者的评论。 “无法编译 max,因为没有用于复数的 运算符 >()”。它抱怨缺少operator &gt;,而不是缺少operator ()。有两件非常不同的事情。不要被() 后面的&gt; 所迷惑
猜你喜欢
  • 1970-01-01
  • 2015-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-25
  • 2013-05-06
相关资源
最近更新 更多