c++ - istream >> ostream << 使用 * 指针重载运算符

标签 c++ pointers operator-overloading istream ostream

如果 >> 和 << 运算符处理指针,我将如何重载它们?

在标题中:

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 。例如,如果您有:

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

..那么你可能会这样做:

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;
}

这个想法是 <<>>理想情况下,运算符应该相互镜像 - 例如,您可以使用它们来序列化和反序列化您的实例。

关于c++ - istream >> ostream << 使用 * 指针重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6105635/

相关文章:

c - void swap(int *a, int *b) 不适用于数组

c - C 和字符串中的 sizeof 操作

c++ - 如何在 C++ 中使用 << 将 unsigned/signed char 或 <cstdint> 类型输出为整数

c++ - 一元 + on 指针

c++ - 编译器如何知道是使用成员运算符重载还是全局运算符重载?

c++ - 无法理解代码片段的返回类型

c++ - 从文件中写入/读取对象

c++ - 从 C++ 调用 sql

c - 如何分配内存并将其返回(通过指针参数)给调用函数?

c++ - 枚举转发声明