C++模拟Java“内部”类
代码思路来自Thinking in C++ 10.13.1内部类方法。类似多重继承,但是类型转换是单向的:Outer支持“向上”转型,但是不能“向下”转型回Outer。
#include <iostream> #include <string> using namespace std; class Interface1 { public: virtual void function1() = 0; }; void CallInterface1(Interface1& if1) { if1.function1(); } class Interface2 { public: virtual void function2() = 0; }; void CallInterface2(Interface2& if2) { if2.function2(); } // Multiple Inheritance class Derived : public Interface1, public Interface2 { public: Derived(const string& nm) : name(nm) {} virtual void function1() { cout << "Call " << name << "'s " << __func__ << endl; } virtual void function2() { cout << "Call " << name << "'s " << __func__ << endl; } private: string name; }; // Mock Inner Class class Outer { public: Outer(const string& nm) : name(nm), inner1(this), inner2(this) {} operator Interface1&() {return inner1;} operator Interface2&() {return inner2;} private: string name; class Inner1; friend class Outer::Inner1; class Inner1 : public Interface1 { public: Inner1(Outer* p) : parent(p) {} virtual void function1() { cout << "Call " << parent->name << "'s function1" << endl; } private: Outer* parent; } inner1; class Inner2; friend class Outer::Inner2; class Inner2 : public Interface2 { public: Inner2(Outer* p) : parent(p) {} virtual void function2() { cout << "Call " << parent->name << "'s function2" << endl; } private: Outer* parent; } inner2; }; int main() { Derived d("Derived Class"); CallInterface1(d); CallInterface2(d); Outer o("Outer Class"); CallInterface1(o); CallInterface2(o); return 0; }
使用聚合代替继承,时间空间的折衷。