【问题标题】:Overloading stream << operator for pointer / shared pointer and other types为指针/共享指针等类型重载流<<操作符
【发布时间】:2019-04-25 07:21:14
【问题描述】:

是否可以为自定义类重载

CustomClass customClass;
std::shared_ptr<CustomClass> sharedPointer(customClass);

os << customClass;
os << sharedPointer;

或者至少以下工作:

os << sharedPointer.get();

默认情况下,使用常用技术重载operator,只有以下2个选项有效:

os << customClass;
os << *sharedPointer.get();

编辑

这里的“工作”意味着,在所有情况下,自定义类 &lt;&lt; 运算符重载都会被执行,并且在所有情况下我都会得到 os &lt;&lt; customClass 的结果,而不是指针类中的指针地址

示例

代码:

os << customClass;
os << sharedPointer;
os << sharedPointer.get();
os << *sharedPointer.get();

输出:

Custom class text
00000244125655C0
00000244125655C0
Custom class text

期望:

第二个或第三个输出也应该是“自定义类文本”

【问题讨论】:

  • 您希望输出什么?地址?
  • 不,这是我得到的。我希望调用包装的自定义类 &lt;&lt; 运算符
  • 修复了术语错误
  • 你是对的,不知道我可以在不调用 get 的情况下取消引用共享指针
  • IMO,将s &lt;&lt; p 输出*p 作为指针p 是一个坏主意,这会使代码更难推理。流式传输指针,我希望在蒸汽中有一个指针。如果我想流式传输对象,我会取消引用指针。你提议的这种超载永远不会通过我的代码审查。

标签: c++ stream operator-overloading


【解决方案1】:

在所有情况下都会执行自定义类

我会这样做:

#include <iostream>
#include <string>
#include <memory>

class MyClass {
    std::string s;

    friend std::ostream& operator<<(std::ostream& os, const MyClass& c) {
        os << c.s;
        return os;
    }

public:
    MyClass(const std::string& s_) : s(s_) {}
};

template<typename T>
std::ostream& operator<<(std::ostream& os, const std::shared_ptr<T>& pc) {
    os << pc.get() << " " << *pc;
    return os;
}    


int main() {
    std::shared_ptr<MyClass> pc = std::make_shared<MyClass>("Hello");
    std::cout << pc << std::endl;
}

输出

0x20f5c30 Hello

查看live example

【讨论】:

  • This 版本没问题,即使与命名空间一起使用也可以工作,因为Argument Dependent Lookup 还包括模板参数(此处为T = MyClass),它会在其中查找适用的函数。但是你会建议把这个通用的operator&lt;&lt; 放在shared_ptr 哪里?
猜你喜欢
  • 2016-11-16
  • 2022-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-11
  • 2017-08-22
  • 1970-01-01
相关资源
最近更新 更多