2011-08-20 81 views
0

我已经写了关系运算符<如类试验超载>作为成员函数

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

这个代码是在头文件,我已经包括在我的.cpp的构件。然而,当我编译我的程序,我得到以下错误:

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

在哪里申报“A”?我应该把它写在我的头文件中作为Test & a? 你能帮我解决这个问题吗?谢谢!

+0

什么是'了'应该是什么?类Test的数据成员?你为什么要将它与'Test'对象进行比较? –

+6

编译器对于你在'a

+0

成员操作符只有一个参数,右边,而'x

回答

2

你应该定义一个Test对象如何与Test类型的另一个对象进行比较,但是在你的代码中你没有定义如何,只有那个“a” - 不管那个是什么,小于另一个对象。

在你的程序
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; 
} 

然后,

// ... 

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

感谢Koan,让我试试这个 – itcplpl

+4

您应该'返回false;'如果if为false或只是使用'return score Voo

+0

okidoki,会这么做...感谢Voo – itcplpl