欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

[C++][设计模式][访问器]详细讲解

最编程 2024-07-05 13:32:08
...
class Visitor; class Element { public: virtual void accept(Visitor& visitor) = 0; // 第一次多态辨析 virtual ~Element(){} }; class ElementA : public Element { public: void accept(Visitor& visitor) override { visitor.visitElementA(*this); } }; class ElementB : public Element { public: void accept(Visitor& visitor) override { visitor.visitElementB(*this); // 第二次多态辨析 } }; class Visitor { public: virtual void visitElementA(ElementA& element) = 0; virtual void visitElementB(ElementB& element) = 0; virtual ~Visitor(){} }; //========================================================= //扩展1 class Visitor1 : public Visitor { public: void visitElementA(ElementA& element) override { cout << "Visitor1 is processing ElementA" << endl; } void visitElementB(ElementB& element) override { cout << "Visitor1 is processing ElementB" << endl; } }; //扩展2 class Visitor2 : public Visitor { public: void visitElementA(ElementA& element) override { cout << "Visitor2 is processing ElementA" << endl; } void visitElementB(ElementB& element) override { cout << "Visitor2 is processing ElementB" << endl; } }; int main() { Visitor2 visitor; // 这里应该用一个基类指针接收 ElementB elementB; elementB.accept(visitor); // double dispatch ElementA elementA; elementA.accept(visitor); return 0; }

推荐阅读