什么是重载流运算符的正确方法< >>为我的类? [英] What's the right way to overload the stream operators << >> for my class?

查看:120
本文介绍了什么是重载流运算符的正确方法< >>为我的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对于如何重载我的类在C + +的流运算符有点困惑,因为它看起来他们是流类,而不是我的类上的函数。什么是正常的方式做到这一点?目前,对于get from运算符,我有一个定义

I'm a bit confused about how to overload the stream operators for my class in C++, since it seems they are functions on the stream classes, not on my class. What's the normal way to do this? At the moment, for the "get from" operator, I have a definition

istream& operator>>(istream& is, Thing& thing) { // etc...

作品。它在Thing类的定义中没有提到。我希望它能够在其实现中访问我的Thing类的成员 - 我该如何做?

which works. It's not mentioned in the definition of the Thing class. I want it to be able to access members of my Thing class in its implementation - how do I do this?

推荐答案

是好的。您需要执行的唯一额外步骤是在 Thing 中将的朋友声明为朋友

Your implementation is fine. The only additional step you need to perform is to declare your operator as a friend in Thing:

class Thing {
public:
  friend istream& operator>>(istream&, Thing&);
  ...
}

这篇关于什么是重载流运算符的正确方法< >>为我的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆