2011-11-24 45 views
0

以下錯誤總是指向我的列表。C++ List Unique()函數

在我的類文件

Point3D operator==(const Point3D &p1) const; 

在我.cpp文件

bool operator==(Point3D &p1, Point3D &p2) 
{ 
    if (p1.getX() == p2.getX() && p1.getY() == p2.getY() && p1.getZ() == p2.getZ()) 
     return true; 
    else 
     return false; 
} 

在我的主文件

//declaration 
list<Point3D> l_3D; 

l_3D.unique(); <-- the error point to this 

錯誤消息

..... In member function 'void std::list<_Tp,_Alloc>::unique() [with_Tp = Point3D,_Alloc = std:: allocator<Point3D>]: 

Instantiated from here 

error: could not convert 'Point3D::operator==(const Point3D&) const (((const Point3D&)((const Point3D*)__next. std::_List_iterator<_Tp>::operator*[with_Tp = Point3D]())))' to 'bool' 

對於那裏的善良的靈魂,我提前感謝你。

+1

此外,而不是'if(some_bool_expression)返回true;否則返回false;',只是有'返回some_bool_expression;'更具慣用性'' –

+1

當人們寫'if(a)返回true時,總會讓我不寒而慄;否則返回false;'而不僅僅是'返回'; : - } –

回答

4

在你的宣言返回Point3D,這應該是bool

Point3D operator==(const Point3D &p1) const; 
^^^^^^^ 
should be bool 

上面看起來像你聲明運營商作爲一個成員函數,賭,那麼你實現它作爲一個免費的功能。你必須決定它是什麼。如果您使用成員函數,改變實施:

bool Point3D::operator==(const Point3D &p2) const 
{ 
    if (getX() == p2.getX() && getY() == p2.getY() && getZ() == p2.getZ()) 
     return true; 
    else 
     return false; 
} 

甚至更​​好(按@ibids評論):

bool Point3D::operator==(const Point3D &p2) const 
{ 
    return (getX() == p2.getX() && getY() == p2.getY() && getZ() == p2.getZ()); 
} 

通常你定義的簽名應匹配的簽名您宣言。

+2

另外,寫'if(...)返回true是不好的風格;否則返回false;'。 – ibid

1

變化:

bool operator==(Point3D &p1, Point3D &p2) 
{ 
    if (p1.getX() == p2.getX() && p1.getY() == p2.getY() && p1.getZ() == p2.getZ()) 
     return true; 
    else 
     return false; 
} 

要這樣:

bool operator==(const Point3D &p1, const Point3D &p2) 
{ 
    if (p1.getX() == p2.getX() && p1.getY() == p2.getY() && p1.getZ() == p2.getZ()) 
     return true; 
    else 
     return false; 
} 
+2

使用此方法時,必須在頭文件的類聲明外寫入聲明(如'class Point3D {}; extern bool operator ==(const Point3D&,const Point3D&);')。 – npclaudiu

0

在類文件(我假設你的意思是一個頭文件),您聲明operator==爲返回Point3D當它應該返回bool。另外,你的operator==在你的類(header?)文件和你的cpp文件中有不同數量的參數。