如何使用多态插入运算符?
How can I use the insertion operator with polymophism
我想实现一个复合模式,可以使用std::cout
打印内容打印时,使用基类插入操作符(operator<<)而不是最派生的类型。如何使用派生最多的类型操作符?
的例子:
#include <iostream>
#include <memory>
using namespace std;
class Base {
int i;
public:
Base(int _i) : i(_i) {}
virtual ~Base() {}
friend inline ostream& operator<<(ostream& os, Base& value) { return os << "i: " << value.i; }
friend inline ostream& operator<<(ostream& os, shared_ptr<Base> value) { return os << "i: " << value->i; }
};
class Derived : public Base {
int x;
public:
Derived(int _x) : Base(2*_x), x(_x) {}
friend inline ostream& operator<<(ostream& os, Derived& value) { return os << "x: " << value.x; }
friend inline ostream& operator<<(ostream& os, shared_ptr<Derived> value) { return os << "x: " << value->x; }
};
int main () {
Base* a = new Base(1);
Derived* d = new Derived(6);
Base* b = new Derived(7);
shared_ptr<Base> ba = make_shared<Base>(3);
shared_ptr<Derived> de = make_shared<Derived>(4);
shared_ptr<Base> bd = make_shared<Derived>(5);
cout << "a is: " << a << endl;
cout << "*a is: " << *a << endl;
cout << "d is: " << d << endl;
cout << "*d is: " << *d << endl;
cout << "b is: " << b << endl;
cout << "*b is: " << *b << endl << endl;
cout << "ba is: " << ba << endl;
cout << "*ba is: " << *ba << endl;
cout << "de is: " << de << endl;
cout << "*de is: " << *de << endl;
cout << "bd is: " << bd << endl;
cout << "*bd is: " << *bd << endl;
delete a;
delete d;
delete b;
return 0;
}
生活代码
This spits out
a is: 0x1fe2bb0
*a is: i: 1
d is: 0x1fe2bd0
*d is: x: 6
b is: 0x1fe2bf0
*b is: i: 14
ba is: i: 3
*ba is: i: 3
de is: x: 4
*de is: x: 4
bd is: i: 10
*bd is: i: 10
但我希望看到*b打印7和bd打印5(即。使用派生类的插入操作符)
好的,在搜索了很多之后,我找到了这个答案。在摇了摇头说了"当然"之后,我总结道:
不要重载插入操作符,因为不能使其为虚函数(它不是成员函数),而是在基类中声明虚函数,并在子类中重写。插入操作符使用以下函数:
class Base {
...
friend inline ostream& operator<<(ostream& os, shared_ptr<Base> value) { return value->display(os, value); }
virtual ostream& display(ostream& os) { os << "i: " << i << endl; }
};
class Derived : public Base {
...
ostream& display(ostream& os) { os << "x: " << x << endl; }
};
生活代码
相关文章:
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 我的运算符重载是否有效<<(流插入)左操作数不是 ostream
- 重载嵌套结构/类的流插入运算符
- 屏幕插入运算符<<的运算符过载问题
- 类方法的C++插入运算符
- 在设计方面:重载vector类型的类成员的插入运算符
- 类重载运算符 '<' 插入指向该对象集的共享指针时不调用
- std::map 索引运算符与插入方法的性能
- 我在C++中遇到插入运算符错误
- 基类和派生类的虚拟插入运算符重载
- 如何在 std::map<const int、int> C++ 中重载插入运算符>>?
- 派生类 插入和提取运算符重载以及基类与派生类之间的强制转换
- 如何将重载>>运算符中输入的值插入到资源库
- 插入运算符的过载与使用二传手功能相比
- Visual Studio 15:重载"<<" C++中的插入运算符
- 使用 std::stringbuf 进行缓冲的效果,同时通过插入运算符'<<'执行写入
- 为什么当我使用额外的括号而不使用运算符重载时,插入运算符在 std::cout 中给出不同的结果?
- 带有指针的重载插入/提取运算符
- 编译器在遇到提取或插入运算符时处理信息(字符串、操纵器等)的顺序是什么?
- 插入运算符无法使用矢量,我不知道为什么