Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/134.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ ==使用结构重载运算符_C++ - Fatal编程技术网

C++ ==使用结构重载运算符

C++ ==使用结构重载运算符,c++,C++,我试图在结构中定义==运算符,如下所示: 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==names,names”必须只包含一个参数 为什么会这样?做: 作为成员职能: struc

我试图在结构中定义==运算符,如下所示:

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==names,names”必须只包含一个参数 为什么会这样?

做:

作为成员职能:

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 */ }
或作为自由函数:

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 */ }
运算符==用于比较两个对象是否相等。它似乎比较了不同物体的名字和姓氏,大概是为了捕捉乔治·拉兹比和艾玛·乔治这样的二重唱

我将其作为类的成员函数,并将其用于其中一个对象:

bool operator== (const names &rhs) const {
    return (this->fname == rhs.fname) && (this->lname == rhs.lname);
}

如果将二进制运算符作为成员函数重载,则它应该只接受一个参数。第一个操作数是调用运算符的对象,即*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更有意义。

您正在作为非静态成员函数进行重载,因此它已经有一个隐式对象参数。将其设为非成员。最好不要按值获取其参数。您的第一个假设应该是编译器是正确的,然后从那里开始。顺便说一句,你比较不同的领域。。。因此,这种比较是不对称的