为什么 test2 + test3 的运算符<<不能过载?
Why can not the operator<< for test2 + test3 be overloaded?
我尝试重载operator<<
,但有一个警告说我不能重载它。我可以按如下方式重载此运算符:
std::cout << test4 << std::endl;
但我不能按如下方式超载它:
std::cout << test2 + test3 << std::endl;
我的主要代码是:
Stonewt test2(2, 8, Stonewt::STONE);
std::cout << "test2: " << test2 << std::endl;
Stonewt test3(2, 3, Stonewt::POUNDS);
std::cout << "test3: " << test3 << std::endl;
Stonewt test4 = test2 + test3;
std::cout << test4 << std::endl; // operator << can overload
std::cout << test2 + test3 << std::endl; // operator << cannot overload
以下是friend
函数
std::ostream& operator <<(std::ostream& os, Stonewt& a)
{
if (a.format == Stonewt::STONE)
{
os << "stone format" << 'n';
os << a.stone << " stones " << a.pound << " pounds" << 'n';
}
else if (a.format == Stonewt::POUNDS)
{
os << "pounds format" << 'n';
os << a.pounds << " pounds" << 'n';
}
else
os << "not valdid" << 'n';
return os;
}
test2+test3
结果是一个临时Stonewt
对象(rvalue(,它不能绑定到non-const
引用(lvalue:即Stonewt &a
(,而是使用const
合格的左值参考。因此,将非成员函数更改为:
std::ostream & operator <<(std::ostream &os, const Stonewt &a)
// ^^^^^^^^^^^^^^^^
{
// ....
return os;
}
延伸阅读:
- 为什么不能传递临时对象作为引用?
- 为什么临时对象可以绑定到常量引用?
- 为什么非常量引用不能绑定到临时对象?
这不是运算符<<不适用于test2 + test3。它缺少运算符+。
您需要重载运算符+,以便"test2 + test3"将起作用。运算符<<的重载正在工作,但编译器在遇到"test2 + test3"时不知道该怎么做,从而发出假定的错误。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么我的for循环不能正确获取argv
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 为什么我不能在 FOR LOOP 中使用 i/10,C++?
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 为什么模板类中的对象不能返回值
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- ld:bind_at_load和-bitcode_bundle(Xcode设置ENABLE_bitcode=YES)不能
- 数组长度,为什么从命令行获取时不能使用它?
- Windows/Cygwin - 不能使用 pybind11 - 犯错误
- 为什么我不能使用 EGL 创建无头 OpenGl 上下文?
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 为什么我不能将 rand() 与数组的大小一起使用?
- 为什么虚函数不能是静态的和全局的?
- 为什么我不能在 while 循环中创建线程?
- 为什么这个音频包络不能通过开关的情况?
- 不能将复制初始化与隐式转换的多个步骤一起使用