C ++与'operator ='不匹配

时间:2015-01-13 15:14:27

标签: c++ assignment-operator

我目前正致力于移动机器人的分配工作。我正在使用Qake-Creator在Windows上开发,使用CMake和Visual C ++ Compiler 10.0。

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

现在问题是关于类Box,它只是存储一些int值:

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。那么这个错误是如何发生的呢?我该如何解决呢?

3 个答案:

答案 0 :(得分:2)

如果要为operator=()类手动实现赋值Box(请注意,编译器将实现默认 成员分配 operator=如果你不提供一个),请考虑遵循这样的模式:

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

    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=(),您可能还需要定义复制构造函数,可能遵循作业{{1}中实现的相同复制逻辑}:

    operator=()

    注意

    您的Box(const Box& src) : cgx ( src.getCenterX() ), cgy ( src.getCenterY() ), endX ( src.getEndX() ), endY ( src.getEndY() ), startX( src.getStartX() ), startY( src.getStartY() ) {} 课程中有一个数据成员name,您正在复制。这是拼写错误吗?你真的确定你不想复制它吗?也许这是一个错误?

答案 1 :(得分:1)

赋值运算符应该接受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

答案 2 :(得分:1)

尝试将参数定义为const:

Box& operator = (const Box &src);                                             

此外,您应该对比较做同样的事情,即使它不是您问题的根源:

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

我怀疑您的作业或比较的右侧是const。请注意,这种模式是很好的做法,因为您没有修改参数。

由于您未能修改const,我还进行了比较this