我正在读一本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个字段的类(两个双打),一个用于实数,一个用于虚数,并且具有>运算符
答案 0 :(得分:4)
问题是您的Complex
类没有定义的operator >
,可在max()
函数中用于比较两个const Complex
对象。
检查是否将operator >
声明为成员函数,该函数是否声明为const
函数或其参数为const
引用。
应该将运算符声明为这样的成员函数:
bool operator >( const Complex & ) const;
,或者,如果它被声明为非成员函数(例如,friend
函数),则应这样声明:
bool operator >( const Complex &, const Complex & );