error: no match for 'operator>' ...

D

Dai Kane

Am experimenting with some range-bound numeric class thingy, and now
wondering this situation:

int a = 10;
myclass b(6);

if ( a > b )
{
...
}

What kind of a operator thingy I need to construct for that to work,
if it's at all possible? And if it's possible... please post the
construct, as I'm rather tired to hunt rarely/"almost-never-used"
stuff with google. Anyway, thanks in advance for answer(s) :)
 
J

John Harrison

Dai Kane said:
Am experimenting with some range-bound numeric class thingy, and now
wondering this situation:

int a = 10;
myclass b(6);

if ( a > b )
{
...
}

What kind of a operator thingy I need to construct for that to work,
if it's at all possible? And if it's possible... please post the
construct, as I'm rather tired to hunt rarely/"almost-never-used"
stuff with google. Anyway, thanks in advance for answer(s) :)

Well there are a few possibilities

The obvious is

bool operator>(int lhs, const myclass& rhs)
{
...
}

Another is this

class myclass
{
public:
myclass(int i)
{
...
}
};

bool operator>(const myclass& lhs, const myclass& rhs)
{
...
}

Here a temporary myclass object will be constructed from the int variable a,
which will then be used to compare with the myclass variable b.

Yet another possibility is

class myclass
{
public:
operator int() const
{
...
}
};

Here the myclass variable b will be automatically converted to an int and
then a ordinary integer comparison will be used.

You choose.

john
 
J

John Harrison

John Harrison said:
Well there are a few possibilities

The obvious is

bool operator>(int lhs, const myclass& rhs)
{
...
}

Reading between the lines, I think you are confused because you are used to
seeing operator defined as part of the class. Like this

class myclass
{
bool operator<(const myclass& rhs) const;
}

and so you don't see how it can be done when the left hand side is not a
class.

Defining an operator as part of a class is OK for assignment operators but
it is usually a bad idea for other operators. Always define operator> and
similar as global functions like this

bool operator>(const myclass& lhs, const myclass& rhs)
{
...
}

The reasons are technical, and I can't be bothered to explain. But it has to
do with the different rules that are applied to the left hand side and right
hand side of an operator when the operator is part of a class. With an
operator like >, you want the same rules on both sides so declaring the
operator outside of a class is better.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,176
Messages
2,570,947
Members
47,498
Latest member
log5Sshell/alfa5

Latest Threads

Top