C++'operator='无法匹敌
C++ no match for 'operator='
我目前正在处理有关移动机器人的分配。我正在使用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=
),请考虑遵循如下模式:
- 使用
const Box&
(不仅仅是Box&
)作为输入源类型,因为您没有修改源; - 检查重载运算符实现 (
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
.
- 为什么 std::optional::operator=(U&&) 要求你是非标量类型?
- 'operator='已弃用:改用 QDir::setPath()
- 过载'operator new'如何导致无限循环?
- 与'operator='不匹配(操作数类型'String'且"void")
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 处理"no operator found"
- 如何编写 operator= 用于使用虚拟方法与非平凡成员的匿名联合
- 运算符重载:"operator+"必须采用零个或一个参数
- 使用 operator() 扩展 Eigen::EigenBase
- 错误消息:使用"string* +="后"no match for 'operator+='"
- 有没有办法修改'operator->',以便'z->im'返回复数的虚部
- "operator +="行为异常的定义
- C++ "error: use of overloaded operator '*' is ambiguous"似乎只有一场比赛
- 错误:二进制'operator*' 'float'和'float[0]'类型的操作数无效
- 在 Eclipse: "error: no match for 'operator='" 中获取错误消息
- 为什么 operator() 处的指针成员不起作用?
- 为什么 string_view::operator== 按值接受参数
- "operator()"在重载运算符方法中是什么意思,在priority_queue(STL)中用作C++中的比较器?
- Valarray 切片数组与 'operator*' 不匹配
- 重载的 operator() 在 Cython 中失败