c++ - c++中关于const成员函数的问题
问题描述
谁能解释我这个错误?这是代码:
class O{
unsigned x;
unsigned y;
public:
O(unsigned x_ ,unsigned y_): x(x_), y(y_){
};
O& operator+= ( O & object){
x += object.x;
}
};
class A {
O item;
public:
A(O i): item(i){;
}
void fun() const{
O j(2,3);
j += item;
}
};
int main(){
return 0;
}
当我尝试编译时,出现此错误:
In member function 'void A::fun() const':
[Error] no match for 'operator+=' (operand types are 'O' and 'const O')
[Note] candidate is:
[Note] O& O::operator+=(O&)
[Note] no known conversion for argument 1 from 'const O' to 'O&'
谁能给我解释一下?如果我将 const 限定符添加到 += 运算符的参数,它会编译。所以我认为问题在于我在 const 函数 fun() 中将对 item 的引用传递给 += 运算符,它是非 const。谁能解释我为什么这是非法的,以及我如何避免犯这种错误,例如,如果在使用 const 限定符等时有一些经验法则可以遵循?
解决方案
这个成员函数
void fun() const{
O j(2,3);
j += item;
}
是一个常数成员函数。因此,调用函数的对象的成员被视为常量成员,特别是在这种情况下,数据成员项被视为声明为
const O item;
在这个表达式中
j += item;
有使用成员函数
O& operator+= ( O & object){
x += object.x;
}
它接受对 O 类型对象的非常量引用。因此,实际上您正在尝试将非常量引用绑定到常量对象。所以编译器发出错误。
上述运算符的参数应使用限定符 const 声明,并具有 return 语句,例如
O& operator+= ( const O & object) {
x += object.x;
return *this;
}
推荐阅读
- java - 寻找设计模式或库
- python - Pyspark 访问和分解 json 的嵌套项
- python - Using apply function to Pandas dataframe
- google-analytics - 事件和目标完成不能一起工作?
- r - 锁定环境但不锁定 .Random.seed
- python - Python散点图:如何使用与颜色周期具有相同颜色的颜色图
- .htaccess - .htaccess 来自旧休息端点新端点的重写请求
- android - 导航架构组件 singleTask 或 singleInstance 在返回堆栈中
- sql-server - 无法使用不同的服务器版本号运行 .sql 脚本
- java - 如何在 Spring Boot API 中实现 RabbitMQ 消费者部分(接收器)