重载流<<运算符,用于指针/共享指针和其他类型的
Overloading stream << operator for pointer / shared pointer and other types
是否可以以以下所有方法都起作用的方式重载自定义类的<<运算符:
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
查看实时示例。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- (C 14)操作员&lt;&lt;超负荷无法正如智能指针向量所预期的那样工作