我想实现一个复合模式,我可以使用std :: cout
打印内容当我打印时,使用基类插入运算符(运算符<&lt ;;)而不是最派生类型。如何使用派生类型最多的运算符?
实施例:
#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;
}
这吐出
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 print 7和bd print 5(即使用Derived类&#39;插入运算符)
答案 0 :(得分:1)
好的,在搜索了很多之后,我找到了this回答。在打了我的脑袋并说“当然&#39;”后,我总结道:
不要重载插入操作符,因为你不能使它成为虚拟的(它不是成员函数),而是在子类中声明一个在子类中重写的虚函数。插入运算符使用此函数:
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; }
};