2009-12-07 54 views
1

我在使用operator ==在以下C++程序中遇到了一些問題。問題與運算符==

#include < iostream> 
using namespace std; 

class A 
{ 
    public: 
     A(char *b) 
     { 
      a = b; 
     } 
     A(A &c) 
     { 
      a = c.a; 
     } 
     bool operator ==(A &other) 
     { 
      return strcmp(a, other.a); 
     } 
    private: 
     char *a; 
}; 


int main() 
{ 
    A obj("test"); 
    A obj1("test1"); 

    if(obj1 == A("test1")) 
    { 
     cout<<"This is true"<<endl; 
    } 
} 

if(obj1 == A("test1"))是怎麼回事?任何幫助表示讚賞。

回答

3
bool operator ==(const A &other) 

使用const引用,所以在if語句中構造的臨時對象可以用作operator ==的參數。

+10

這是錯誤的答案。 strcmp問題是正確的。 – 2009-12-07 13:49:41

+0

感謝您的快速回復!我觀察到的一件事是這個工作拷貝構造函數的參數也應該是const。 A(const A&c) – CPPDev 2009-12-07 13:53:43

+0

您能否以清晰的答案爲例? – Ashish 2009-12-07 13:59:36

34

strcmp返回0,當字符串是平等的,所以你想:

return strcmp(a, other.a) == 0; 

您還應該使用像克特林Pitiş一個const引用他回答說,因爲這樣你可以使用臨時對象與運營商,你也應該使方法本身const(因爲它不會修改對象),正如Andreas Brinck在下面的評論中所說的那樣。所以,你的方法應該是:

bool operator ==(const A &other) const 
{ 
     return strcmp(a, other.a) == 0; 
} 
+2

這些函數也應該是const的:'bool operator ==(const A&other)const' – 2009-12-07 13:52:03

2

它像你想這在你的運營商看上去對我說:

strcmp(a, other.a) == 0 

strcmp返回0時字符串匹配,並表示數比較是大還是小否則。

-1

您的錯誤是您創建一個即時值並將其作爲參考傳遞給operator==方法。但是,你的錯誤是在您的運營商的定義應該是:

布爾運算符==(const的一個&等)const的

身體是相同的。

+0

添加const stuff絕對是一個好主意,_just_添加const「body正文相同」會導致相同的錯誤行爲作爲原始程序。 – 2009-12-07 14:15:53

+0

更正:在某些平臺上,常量不僅僅是一個好主意,它是必需的。正確的行爲仍然需要邁克的'strcmp'更改。 – 2009-12-07 16:14:29