重载操作符
Overloaded Operators
我有一个名为"Students"的类,其中一个变量是包含学生姓名的字符串。
我想重载">"操作符,这样它就可以测试第一个学生的名字是否比第二个学生的名字长,我想让它返回一个bool (true或false)值。
bool operator>(Students student1, Students student2)
{ //code to compare the two strings}
我一直得到一个错误,说我有太多的参数
你的参数太多了。
重载操作时,第一个隐式形参是当前对象,也称为this
。
所以你想:
class Students
{
/*Param #1 is THIS*/
bool operator>(Students& student2)
{
return (this->name.Length > student2.name.Length);
}
}
的用法是这样的:
void MyFunc()
{
Students alpha("Eric");
Students beta("Sampson");
if (alpha > beta) // effectively calls alpha.OperatorGreater(alpha, beta)
}
将比较操作符声明为非成员函数或成员函数。请参阅下面的示例,这两个示例都可以正常工作。
非成员函数版本:
using namespace std;
struct s {
double a;
s(double aa): a(aa) {};
};
bool operator< (const s &s1, const s &s2) {
return s1.a < s2.a;
}
int main() {
s s1(1);
s s2(2);
bool b = s1 < s2;
}
成员函数版本:
using namespace std;
struct s {
double a;
s(double aa): a(aa) {};
bool operator< (const s &s2) { return a < s2.a ;}
};
int main() {
s s1(1);
s s2(2);
bool b = s1 < s2;
}