class Window { public: Window(const int size) : _size(size) {} virtual ~Window() {} virtual void onResize(const int size) {_size = size;} int GetSize() const {return _size;} private: int _size; }; class GlassWinsow : public Window { public: GlassWinsow(const int size, const int gSize) : Window(size), _gSize(gSize) {} void onResize(const int size, const int gSize) { static_cast<Window>(*this).onResize(size); _gSize = gSize; } int GetGlassSize() const {return _gSize;} private: int _gSize; };调用
GlassWinsow gw(2, 3); cout<<"Window size:"<<gw.GetSize()<<" GlassWindow size:"<<gw.GetGlassSize()<<endl; gw.onResize(4, 5); cout<<"Window size:"<<gw.GetSize()<<" GlassWindow size:"<<gw.GetGlassSize()<<endl;结果
void onResize(const int size, const int gSize) { Window::onResize(size); _gSize = gSize; }同样调用结果
void blink() {cout<<"GlassWindows Link\n";}这样调用
typedef std::vector<std::tr1::shared_ptr<Window>> VPW; VPW winPtrs; winPtrs.push_back(std::tr1::shared_ptr<Window>(new GlassWinsow(2, 3))); for (VPW::iterator iter = winPtrs.begin(); iter != winPtrs.end(); ++iter) { if(GlassWinsow* psw = dynamic_cast<GlassWinsow*>(iter->get())) psw->blink(); }我们应该改成下面的调用方式
typedef std::vector<std::tr1::shared_ptr<GlassWinsow>> VPSW; VPSW winPtrs; winPtrs.push_back(std::tr1::shared_ptr<GlassWinsow>(new GlassWinsow(2, 3))); for (VPSW::iterator iter = winPtrs.begin(); iter != winPtrs.end(); ++iter) { (*iter)->blink(); }这种做法无法在同一个容器内存储指针“指向所有可能之各种Window派生类”。在Window上继承,那么就要定义多个类型的容器
class Window { public: Window(const int size) : _size(size) {} virtual ~Window() {} virtual void onResize(const int size) {_size = size;} int GetSize() const {return _size;} virtual void blink() {} private: int _size; }; class GlassWinsow : public Window { public: GlassWinsow(const int size, const int gSize) : Window(size), _gSize(gSize) {} void onResize(const int size, const int gSize) { Window::onResize(size); _gSize = gSize; } int GetGlassSize() const {return _gSize;} void blink() {cout<<"GlassWindows Link\n";} private: int _gSize; }; class WoodWindow : public Window { public: WoodWindow(const int size, const int gSize) : Window(size), _gSize(gSize) {} void onResize(const int size, const int gSize) { Window::onResize(size); _gSize = gSize; } int GetGlassSize() const {return _gSize;} void blink() {cout<<"WoodWindow Link\n";} private: int _gSize; };调用
typedef std::vector<std::tr1::shared_ptr<Window>> VPSW; VPSW winPtrs; winPtrs.push_back(std::tr1::shared_ptr<Window>(new GlassWinsow(2, 3))); winPtrs.push_back(std::tr1::shared_ptr<Window>(new WoodWindow(4, 5))); for (VPSW::iterator iter = winPtrs.begin(); iter != winPtrs.end(); ++iter) { (*iter)->blink(); }GlassWindows Link
原文地址:http://blog.csdn.net/hualicuan/article/details/28292019