如何正确定义和调用原始运算符<<
How to properly define and call original operator<<
请考虑以下示例:
#include <iostream>
class A {
const int i;
const int j;
public:
A(int i_, int j_) : i(i_), j(j_) {}
std::ostream& operator<<(std::ostream& o) const {
o << "i is " << i << ", j is " << j;
return o;
}
};
std::ostream& operator<<(std::ostream& o, const A& a ) {
o << "This is A: ";
a.operator<<(o);
return o;
}
int main() {
A a(0,42);
std::cout << a << std::endl;
return 0;
}
它将生成以下输出:
This is A: i is 0, j is 42
输出是正确的,但我不喜欢我如何称呼 A 的原始operator<<
.
我正在尝试弄清楚如何正确定义该运算符,因此可以这样调用它:
o << "This is A: " << (some magic)a;
而不是
o << "This is A: ";
a.operator<<(o);
我已经尝试了各种方法,但要么我遇到了歧义问题,要么得到了std::cout
和断开字符串的地址。请注意,A::operator<<
的结果std::ostream&
是我的测试的残余。在上面的例子中,使用 void
就足够了。
是否可以不创建一个从A类派生的中间类B并定义自己的运算符<<(class NiceOutputOfA : public A {...};
(?
在类中定义的二元运算符始终将类作为左侧操作数。这意味着您无法在类中实现流插入/提取。
可能最常见的方法是将运算符实现为类中内联定义的friend
。
另一种合理的常见方法是在类中提供一个命名的流函数,以及一个调用该函数的类外流运算符。您几乎做到了,但将该函数命名为 operator <<
。
我得出的最接近的解决方案是通过创建一个中间类:
class Decorate {
const A& a;
public:
Decorate(const A& a_) : a(a_) {}
friend std::ostream& operator<<(std::ostream& o, const PrintA& pa) {
o << "This is A: " << pa.a;
return o;
}
};
并以这种方式打印它:
int main() {
A a(0,42);
std::cout << Decorate(a) << std::endl;
return 0;
}
我一直在寻找更漂亮的东西,但根据 Angew 的回答,我失去了起诉正确operator<<
声明的希望。
感谢您的帮助!将安格的回应标记为答案。
相关文章:
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 如何显式调用运算符<<
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- C++运算符<<调用::ostream而不是std::osttream
- BOOST ::变体无法解决运算符&lt;&lt;对于STD :: Ostream
- 过载输出<<用于类的运算符,以打印其中的元组
- C++ostream:没有运算符匹配<<&应在'&'代币
- 重载运算符<<:此运算符函数的参数太多
- C++继承运算符<<
- 重载运算符<<用于模板类.即使使用好友关键字也无法获得私人会员
- 如何过载<<用于YAML::Emitter的运算符,以序列化包含另一个自定义类的向量的自定义类
- 为什么字符串流运算符<<擦除原始值
- 关于使用运算符<<为新手提供C++中的模板
- 我已经完成了<<运算符重载,但它'It’不起作用
- 重载运算符<<输出地址而不是数据成员
- 错误:没有匹配'运算符<<"在'std::cout
- 重载运算符<<用于ostream语法
- 当运算符<存在时,为什么要定义 LT?
- log4cxx访问异常,使用<<运算符和宏
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多