istream>> ostream<<带有*指针的运算符重载 [英] istream >> ostream << Operator Overloading with * Pointer

查看:118
本文介绍了istream>> ostream<<带有*指针的运算符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何重载>>和<<运算符是否正在处理指针?

How would I overload the >> and << operators if they are dealing with pointers?

标题中:

friend std::istream& operator >>( std::istream& ins, Classname* & e);
friend std::ostream& operator <<( std::ostream& outs, const Classname * e);

在cpp中:

std::ostream& operator <<( std::ostream& outs, const Classname * e)
{   // what do I do here?
return outs;
}
std::istream& operator >>( std::istream& ins, Classname* & e){
// what do I do here?
    return ins;
}

推荐答案

这取决于类Classname中的内容.例如,如果您有:

It depends on what is in the class Classname. If for example you have:

class Classname {
//...
private:
  int a;
};

..那么您可以这样做:

.. then you might do:

std::ostream& operator <<( std::ostream& outs, const Classname * e)
{  
  outs << e->a;
  return outs;
}
std::istream& operator >>( std::istream& ins, Classname* & e){
    ins >> e->a;
    return ins;
}

<<>>运算符在理想情况下应该相互镜像-因此,例如,您可以利用它们对您的实例进行序列化和反序列化.

The idea being that the << and >> operators ideally should mirror each other - so for example you can make use of them for serializing and deserializing your instances.

这篇关于istream&gt;&gt; ostream&lt;&lt;带有*指针的运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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