gpt4 book ai didi

c++ - 如何正确定义和调用原始运算符<<

转载 作者:行者123 更新时间:2023-11-30 02:21:45 25 4
gpt4 key购买 nike

考虑以下示例:

#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 的地址和断弦。请注意结果 std::ostream&A::operator<<是我测试的残余。在上面的示例中,使用 void 就足够了.

是否可以不创建从类 A 派生并定义自己的运算符 << ( class NiceOutputOfA : public A {...}; ) 的中间类 B?

最佳答案

类内定义的二元运算符始终将类作为左侧操作数。这意味着您不能在类里面实现流插入/提取。

可能最常见的方法是将运算符实现为 friend在类中内联定义。

另一种相当常见的方法是在类中提供一个命名的流函数,以及调用该函数的类外流运算符。您几乎做到了,但是将该函数命名为 operator << .

关于c++ - 如何正确定义和调用原始运算符<<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48010311/

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