C++ 与‘不匹配;运算符==’;在‘;a==b’;

C++ 与‘不匹配;运算符==’;在‘;a==b’;,c++,C++,为什么会出现此错误消息? 此外,我想知道为什么(const family&,const family&)中有参考符号“&”。 请给我一些修改代码b.b的建议。如果将操作符==实现为成员函数,它只需要一个参数 或者在实践中,您可以将其作为自由函数实现 "no match for ‘operator ==’ in ‘a == b’" 更新: 由于operator==接受常量族对象,因此需要使getWight()/getHeight()函数常量 为什么会出现此错误消息 如果将二进制运算符实现为成员函

为什么会出现此错误消息? 此外,我想知道为什么(const family&,const family&)中有参考符号“&”。
请给我一些修改代码b.b的建议。

如果将
操作符==
实现为成员函数,它只需要一个参数

或者在实践中,您可以将其作为自由函数实现

"no match for ‘operator ==’ in ‘a == b’"
更新: 由于
operator==
接受常量族对象,因此需要使
getWight()/getHeight()
函数常量

为什么会出现此错误消息

如果将二进制运算符实现为成员函数,则它只接收右侧作为参数,左侧是调用对象。如果你写:

class family
{
private:
        double weight;
        double height;
public:
        family(double x,double y); 
        ~family();
        double getWeight() const;
        double getHeight() const;
        double setWeight();
        double setHeight();
};

bool operator==(const family &a,const family &b)
{
   return a.getWeight() == b.getWeight();
}
编译器将查找满足以下条件之一的函数:

a == b

注意:(返回类型)可以是任何内容,但通常您希望在此处返回bool。它不会影响编译器在进行函数调用时查找的内容

您的函数签名改为:

(return type) operator==( (type of lhs), (type of rhs) );
这需要三个参数(一个隐含参数)


此外,我想知道为什么(const family&,const family&)中有参考符号“&”

const family&
是函数接受的参数类型。它通过引用接收
系列
类型的对象(即,它使用原始对象而不是复制它们),并承诺不修改它们(
const
)。编译器将执行这一承诺。由于函数不需要修改任何一个对象,也没有理由制作任何一个对象的完整副本,因此这正是使用的正确签名。对于非成员函数

对于成员函数,您必须稍微修改它:

(return type) (type: family)::operator==( (type: family), (type: family) );
到目前为止还可以,我们不需要改变任何事情。您的参数列表应仅包含右侧参数,因此:

class family
{   // ...
    bool operator==(
    // ...
}
但我们还没有完成。还记得非成员函数如何使用“const family&”作为参数类型吗?不知何故,我们也需要将调用对象标记为const。为此,我们在末尾添加常量:

bool operator==(const family&)
(调用对象已可用,就像通过引用一样。)


在编写函数本身时,只需使用:

bool operator==(const family&) const;
然后,对于函数体,您可以直接使用调用对象和rhs的成员,或者调用它们的相关函数,如下所示:

bool family::operator==(const family &rhs) const {
    ...
}


您可以对代码进行以下更改:

    return getWeight() == rhs.getWeight(); // using functions

两种可能性: (1) 如果要保持定义不变,请执行以下操作: 声明为非会员和朋友:

bool family::operator==(const family &b) 
{
        return weight == b.getWeight();
}   
bool operator ==(const family &a,const family &b) 
{
        return(a.getWeight() == b.getWeight());
}   
定义为:

friend bool operator==(const family &,const family &); 
bool operator==(const family &); 
(2) 声明为成员(隐式参数是此参数指向的当前对象): 声明为非会员和朋友:

bool family::operator==(const family &b) 
{
        return weight == b.getWeight();
}   
bool operator ==(const family &a,const family &b) 
{
        return(a.getWeight() == b.getWeight());
}   
定义为:

friend bool operator==(const family &,const family &); 
bool operator==(const family &); 
bool operator==(const family &); 
bool family::operator ==(const family &a) 
{
        return(this->getWeight() == a.getWeight());
}