C ++()运算符重载,它的工作是什么

时间:2020-06-01 20:35:50

标签: c++ templates operator-overloading operators

我正在读一本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个字段的类(两个双打),一个用于实数,一个用于虚数,并且具有>运算符

1 个答案:

答案 0 :(得分:4)

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

检查是否将operator >声明为成员函数,该函数是否声明为const函数或其参数为const引用。

应该将运算符声明为这样的成员函数:

bool operator >( const Complex & ) const;

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

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