重载流<<运算符,用于指针/共享指针和其他类型的

Overloading stream << operator for pointer / shared pointer and other types

本文关键字:指针 lt 类型 共享 其他 用于 运算符 重载      更新时间:2023-10-16

是否可以以以下所有方法都起作用的方式重载自定义类的<<运算符:

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

或者至少以下作品:

os << sharedPointer.get();

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

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

编辑

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

法典:

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

输出:

Custom class text
00000244125655C0
00000244125655C0
Custom class text

期望:

在第二个或第三个输出也应该是"自定义类文本">

在所有情况下都会执行自定义类<<运算符重载,并且我在所有情况下都得到 os <<customClass 的结果,而不是指针类情况下的指针地址

以下是我会怎么做:

#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

查看实时示例。