user13659234
user13659234

Reputation:

C++, () operator overloading, what's its job

I was reading from a book in C++ and it says:

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;
}

What does that mean, where did I used the () operator for Complex numbers here and what's its job in general? (I don't understand the whole idea behind () operator even though I read about it)

Complex is a class with 2 fields one (two doubles) one for real number and one for imaginary number, plus it has > operator

Upvotes: 1

Views: 62

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

The problem is that your Complex class does not have an operator > defined that could be used within the max() function to compare two const Complex objects.

Check if the operator > is declared as a member function, whether the function is declared as a const function, or its parameter is a const reference.

The operator should be declared either as a member function like this:

bool operator >( const Complex & ) const;

or, if it is declared as a non-member function (for example as a friend function), then it should be declared like this:

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

Upvotes: 4

Related Questions