2014-09-11 34 views
-2

我想一个结构中定义的==操作符重载,就像这样:==操作符与结构

struct names { 
    string fname; 
    string lname; 
bool operator==(names a, names b) { 
    return (a.fname == b.lname); 
} 
}; 

然而,编译器说:

..\src\trash.cpp:10:33: error: 'bool names::operator==(names, names)' must take exactly one argument

这是为什么?

+3

你正在做重载作为非静态成员函数,所以它已经有了一个隐含的对象参数。 – 2014-09-11 07:32:47

+0

使其成为非会员。 – juanchopanza 2014-09-11 07:33:09

+1

最好不要以价值观来论证它的论点。 – 2014-09-11 07:34:11

回答

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会更有意义。)

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 */ } 
    
0

operator==是为了比较两个对象是否相等。你看起来似乎是为了比较不同物体的名字和姓氏,大概是为了找到像乔治拉曾比和艾玛乔治这样的二重奏。

我会做它的类的成员函数,并使用this的对象之一:

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