2009-12-07 55 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