gpt4 book ai didi

c++ - 重载 + 运算符以能够处理对象的 3 个 const 实例

转载 作者:太空宇宙 更新时间:2023-11-04 15:22:24 25 4
gpt4 key购买 nike

我在为我的 CMatrix 类中的 const 实例定义重载运算符 + 时遇到了问题。我已经得到了 + operator 的定义CMatrix 运算符+(const CMatrix &matrix) const;

它适用于 CMatrix 的 非常量 实例。但我不能做这样的事情:

const CMatrix a;
const CMatrix b;
const CMatrix c;
a=b+c;

尝试编译源代码时出现此错误:错误:将“const CMatrix”作为“CMatrix& CMatrix::operator=(const CMatrix&)”的“this”参数传递会丢弃限定符

谁能告诉我,如何定义 + operator 的重载以便能够编译代码?

最佳答案

这与您的operator+ 没有任何关系。这是因为您试图分配给 a,即使您将其声明为 const。您显然不能分配给 const 对象,因为那样会改变它的值!

也许你想这样做:

const CMatrix a = b + c;

或者使 a 成为非 const

关于c++ - 重载 + 运算符以能够处理对象的 3 个 const 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15856971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com