2014-09-11 72 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); 
}