开发者

overloading > as member function

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

bool Test::operato开发者_如何转开发r<(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!


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";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜