为什么不能重载 test2 + test3 的 operator<<?
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
限定的 lvalue 引用。因此将非成员函数改为:
std::ostream & operator <<(std::ostream &os, const Stonewt &a)
// ^^^^^^^^^^^^^^^^
{
// ....
return os;
}
进一步阅读:
- Why can't pass temporary object as reference?
- How come a non-const reference cannot bind to a temporary object?
这不是 operator<< 不适用于 test2 + test3。它缺少一个运算符+。
您需要重载 operator+ 以便 'test2 + test3' 起作用。 operator<< 的重载有效,但编译器在遇到 'test2 + test3' 时不知道该怎么做,因此发出假定的错误。
我尝试使 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
限定的 lvalue 引用。因此将非成员函数改为:
std::ostream & operator <<(std::ostream &os, const Stonewt &a)
// ^^^^^^^^^^^^^^^^
{
// ....
return os;
}
进一步阅读:
- Why can't pass temporary object as reference?
- How come a non-const reference cannot bind to a temporary object?
这不是 operator<< 不适用于 test2 + test3。它缺少一个运算符+。
您需要重载 operator+ 以便 'test2 + test3' 起作用。 operator<< 的重载有效,但编译器在遇到 'test2 + test3' 时不知道该怎么做,因此发出假定的错误。