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";
精彩评论