C++'operator='无法匹敌

C++ no match for 'operator='

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

我目前正在处理有关移动机器人的分配。我正在使用QT-Creator在Windows上开发,使用CMake和Visual C++ Compiler 10.0。

当机器人在 Ubuntu 上工作时,我需要在 Ubuntu 上使用 QT-Creator 和 GNU x86 编译器编译 projekt。

现在问题来了,关于类Box,它只是存储一些整数值:

盒子.h

public:
Box();                                                                  
Box(int name, int sX, int sY, int width, int heigth);               
Box& operator = (Box &src);                                             
bool operator == (Box &src);                                     
private:
int name;                                                              
int startX, startY, endX, endY;                                       
int cgx, cgy;                                                        
int width, height;

这个标头中也有一些get方法(如int getName())。

重载赋值运算符如下所示:

Box &Box::operator =(Box &src){
    this->cgx = src.getCenterX();
    this->cgy = src.getCenterY();
    this->endX = src.getEndX();
    this->endY = src.getEndY();
    this->startX = src.getStartX();
    this->startY = src.getStartY();
   return *this;} 

我在另一个类中使用 Box 对象,存储在std::list<Box>中。

在Windows上,一切正常。但是在 Ubuntu 上我收到错误消息 no match for 'operator=' (operand types are 'Box' and 'const Box') ,它发生在 std::list 的函数中。

我对C++很陌生,没有在任何地方使用const明确的。那么这个错误是如何发生的,我该如何解决呢?

如果要手动实现Box类的赋值operator=()(请注意,如果您不提供赋值,编译器将实现默认的成员赋值operator=),请考虑遵循如下模式:

  1. 使用 const Box&(不仅仅是 Box&)作为输入源类型,因为您没有修改源;
  2. 检查重载运算符实现 ( if (&src != this)... ) 中的自赋值。

在代码中:

Box& Box::operator=(const Box& src) 
{
    if (&src != this) 
    {
        this->cgx = src.getCenterX();
        this->cgy = src.getCenterY();
        this->endX = src.getEndX();
        this->endY = src.getEndY();
        this->startX = src.getStartX();
        this->startY = src.getStartY();
    }
    return *this;
} 

另请注意,如果您手动定义复制赋值operator=(),您可能还需要定义一个复制构造函数,可能遵循在赋值operator=()中实现的相同复制逻辑:

Box(const Box& src) :
    cgx   ( src.getCenterX() ),
    cgy   ( src.getCenterY() ),
    endX  ( src.getEndX()    ),
    endY  ( src.getEndY()    ),
    startX( src.getStartX()  ),
    startY( src.getStartY()  )
{}

注意

Box类中有一个复制的数据成员name。这是错别字吗?你真的确定你不想复制它吗?也许这是一个错误?

值运算符应该接受一个 const 对象:

Box& operator = (const Box& src);

因为它不会影响src而只会this.

定义复制

运算符时,还应定义复制构造函数。请参阅 http://en.cppreference.com/w/cpp/language/rule_of_three

比较运算符应该接受一个 const 对象并且应该是 const(函数不会更改this)。

bool operator == (const Box& src) const;

因为它不会影响src,也不会影响this

尝试将参数定义为 const:

Box& operator = (const Box &src);                                             

此外,您应该对比较执行相同的操作,即使它不是问题的根源:

bool operator == (const Box &src) const;  

我怀疑你的作业或比较的右手边是const.请注意,此父项是很好的做法,因为您不会修改参数。

我也做了比较const,因为你不会修改this.