我试图在结构中定义一个==运算符,如下所示:
struct names {
string fname;
string lname;
bool operator==(names a, names b) {
return (a.fname == b.lname);
}
};
然而,编译器说:
.. \ src \ trash.cpp:10:33:错误:' bool names :: operator ==(姓名,姓名)'必须采取一个参数
为什么会这样?
答案 0 :(得分:3)
如果将二元运算符作为成员函数重载,那么它应该只接受一个参数。第一个操作数是调用操作符的对象(即*this
);第二个操作数是单个函数参数。
struct names {
//...
// better to pass by reference;
// make the function 'const' so it can be used on constant objects
bool operator==(names const & rhs) const {
return this->fname == rhs.lname;
}
};
或者,您可以将其作为非成员函数重载,并带有两个参数:
bool operator==(names const & lhs, names const & rhs) {
return lhs.fname == rhs.lname;
}
如果这需要访问私有成员(在本例中不是这种情况),那么它必须是朋友。您可以在类定义中定义朋友;在这种情况下,代码看起来与您的示例完全相同,只是在函数声明前面有friend
。
(当然,这不是一个明确的平等定义,因为它不是对称的。如果你可以a == b
而不是b==a
,很多算法都会破坏,就像你可以这样定义。lhs.fname == rhs.fname && lhs.lname == rhs.lname
会更有意义。)
答案 1 :(得分:0)
执行:
作为会员功能:
struct names {
string fname;
string lname;
bool operator==(const names& rhs) const { /* Your code */ }
};
或作为自由功能:
bool operator==(const names& lhs, const names& rhs) const { /* Your code */ }
答案 2 :(得分:0)
operator==
旨在比较两个对象的相等性。你看起来比较不同对象的名字和姓氏,可能是为了捕捉乔治·拉赞比和艾玛·乔治这样的二重唱。
我将它作为该类的成员函数,并使用this
作为其中一个对象:
bool operator== (const names &rhs) const {
return (this->fname == rhs.fname) && (this->lname == rhs.lname);
}