C++ List Unique() Function

C++ List Unique() Function

本文关键字:Function Unique List C++      更新时间:2023-10-16

下面的错误总是指向我的List

在class文件

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'

对于那些善良的灵魂,我提前感谢你们。

在您的声明中,您返回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());
}

一般来说,定义的签名应该与声明的签名匹配。

变化:

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;
}

在您的类文件中(我假设您的意思是头文件),您声明operator==为返回Point3D时,它应该返回bool。此外,您的operator==在您的类(头?)文件和您的cpp文件中具有不同数量的参数。