输入对象没有 const 的 C++ 重载 << 会产生错误,该错误随 const 对象一起消失

标签 c++ compiler-errors operator-overloading constants

我有以下运算符重载原型(prototype):

 ostream& operator<<(ostream & outputstream, my_arr& arr)

 my_arr operator+(const my_arr& left, const my_arr& right)

我打电话:

 cout << (arr1 + arr2);

这给了我以下编译器错误:

error: no match for ‘operator<<’ in ‘std::cout << operator+(const my_array&, const my_array&)((*(const my_array*)(& y)))’

如果我将 << 的签名更改为以下内容,这就会消失:

  ostream& operator<<(ostream & outputstream, const my_arr& arr)

我可能在这里遗漏了一些基本的东西,但为什么会这样呢? 感谢您的帮助。

最佳答案

问题在于,当作为引用传递时,您不能传递“临时”(右值)对象,例如加法的结果。当传递一个 const 引用时,C++ 规则允许传递临时对象,因为它保证它们不会被写入。

关于输入对象没有 const 的 C++ 重载 << 会产生错误,该错误随 const 对象一起消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14393614/

相关文章:

android - C++ JNI 互操作性

c# - 将隐式转换为具体类型的结果存储到接口(interface)中失败

c# - 如果我将任何代码添加到我的 Main 方法,Visual Studio Giving 编译器错误

c++ - 在具有 2 个模板的模板类中重载 operator+

c++ 函数——哪个日期是第一个/最后一个?

c++ - 无法设置 ostringstream 对象的 streambuf

c++ - 为什么 std::distance 会出现在 STL map 中?

visual-c++ - 警告MSB8012 : TargetPath(C:\wxWidgets-2.9.1\build\wx291_msw_vc10\..\..\lib\vc_lib\wxregex.lib) does not match

c++ - C++ 中逗号分隔值的 `operator<<`

c++ - 隐式转换不适用于 BOOST_STRONG_TYPEDEF 和 BOOST_SPIRIT_DEBUG_NODE