0

I have written a relational operator < as member of class Test

bool Test::operator<(const Test& t) { if (a<t) return true; } 

this code is in the header file, which I have included in my .cpp. However, when I compile my program, I get the following error:

test.h: 134:6: error: ‘a’ was not declared in this scope 

Where do I declare 'a'? should I write it in my header file as Test& a? can you please help me fix this. thx!

10
  • What is a supposed to be? A data member of class Test? And why are you comparing it against a Test object? Commented Aug 20, 2011 at 23:00
  • 6
    The compiler is confused as to what you mean by a in a<t. So are we. Please explain. Commented Aug 20, 2011 at 23:01
  • The member operator only takes one argument, the right-hand side, and x < y invokes x.operator<(y)... so you need to compare your argument t to the instance itself. Commented Aug 20, 2011 at 23:01
  • @Kerrek That's correct but hopefully the OP will not run with this advice in the absolute literal sense, because an implementation like *self<t would be circular. :-) Commented Aug 20, 2011 at 23:09
  • @Ray: sure - since the OP is overloading a comparison operator, I'm sort of assuming that she knows that the purpose of this is to define the comparison semantics. By the way, in C++ it's called this (not "self") :-) Commented Aug 20, 2011 at 23:12

1 Answer 1

2

You're supposed to be defining how a Test object may be compared to another object of type Test but in your code you do not define how, only that "a" - whatever that is, is less than the other object.

class Test { public: Test(int myscore) { score = myscore; } bool operator<(const Test &t); int score; } bool Test::operator<(const Test &t) { // Is less than if score is smaller if(score < t.score) return true; else return false; } 

Then in your program,

// ... Test test1(4); Test test2(5); if(test1 < test2) std::cout << "4 is less than 5 by comparing objects\n"; else std::cout << "Failed!\n"; 
Sign up to request clarification or add additional context in comments.

3 Comments

You should either return false; if the if is false or just use return score < t.score to begin with. Otherwise you'll get strange behavior.
Good catch @Voo, I was trying too hard to make the given code work. It should have been a compiler error when the function didn't return false.
If you make operator< a member of the class, you should probably make it const, too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.