"Cannot convert 'MyClass' to 'bool'" Error in Template Programming
I am playing around with templates and have t开发者_开发问答ried the following but get 'Cannot convert 'MyClass' to 'bool' error?
#include "Unit2.h"
using namespace std;
template <class T>
T GetMax (T a, T b) {
T result;
result = (a > b) ? a : b;
return (result);
}
int main () {
MyClass k1( 10, "A" );
MyClass k2( 50, "B" );
MyClass k3( 0,"" );
k3 = GetMax<MyClass>(k1,k2);
cout << k3.GetName() << endl;
return 0;
}
//---------------------------------------------------------------------------
I have defined a > operator for myclass as follows:
MyClass& MyClass::operator>(MyClass &rhs)
{
MyClass& rkReturn = ( m_iSize > rhs.m_iSize ) ? *this : rhs;
return rkReturn;
}
Your >
operator should return a bool
, not a MyClass
reference.
Your operator>
returns a MyClass&
instead of a bool
. By using it in the conditional operator, the compiler is trying to coerce the returned MyClass
to a bool
.
Change
MyClass& MyClass::operator>(MyClass &rhs)
{
MyClass& rkReturn = ( m_iSize > rhs.m_iSize ) ? *this : rhs;
return rkReturn;
}
to
bool MyClass::operator>(const MyClass &rhs) const
{
return m_iSize > rhs.m_iSize;
}
The syntax x ? y : z
requires x to be convertable to a bool
type. You give it the expression (a > b)
, which calls your operator MyClass& MyClass::operator>(MyClass &rhs)
, which returns a MyClass
by reference. The compiler cannot convert this reference to a bool
, and gets confused. MyClass::operator>(MyClass &rhs)
should return a bool
.
bool MyClass::operator>(MyClass &rhs) const //also, it should be a const function
{
return m_iSize > rhs.m_iSize
}
Your >
operator needs to return a bool
(or something that can be automatically converted to a bool
, such as an int
), not a MyClass&
.
You need to return bool
from operator>
.
So try this:
bool MyClass::operator>(const MyClass &rhs)
{
return m_iSize > rhs.m_iSize;
}
It would be better if you make this a const
function, by putting the keyword on the right side of the function, as shown below:
bool MyClass::operator>(const MyClass &rhs) const
{ // ^^^^^ this makes the function const
return m_iSize > rhs.m_iSize;
}
Put const
on the declaration also.
operator> should be declared/defined to return bool, not MyClass&.
operator >
should return bool and not MyClass &
like this:
bool MyClass::operator>(MyClass &rhs)
{
return m_iSize > rhs.m_iSize;
}
Try this
bool MyClass::operator>(MyClass &rhs)
{
return m_iSize > rhs.m_iSize ;
}
The operator>
for MyClass
should simply define whether one instance of the class is greater than the other, and it should return type bool
, not type MyClass&
. Modify it so that it looks like the following:
bool MyClass::operator>(const MyClass &rhs) const
{
return m_iSize > rhs.m_iSize;
}
This will now properly test whether the current instance of MyClass
is larger than the MyClass
instance on the right-hand side of the >
operator in such an expression.
精彩评论