zoukankan      html  css  js  c++  java
  • the “inner class” idiom

    有些时候我们需要upcast为多种类型,这种情况下除了可以使用multiply inherits还可以inner class。
    以下为例子:

    //: C10:InnerClassIdiom.cpp
    // Example of the "inner class" idiom.
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Poingable {
    public:
      virtual void poing() = 0;
    };
    void callPoing(Poingable& p) {
      p.poing();
    }
    
    class Bingable {
    public:
      virtual void bing() = 0;
    };
    void callBing(Bingable& b) {
      b.bing();
    }
    
    class Outer {
      string name;
      // Define one inner class:
      class Inner1;
      friend class Outer::Inner1;
      class Inner1 : public Poingable {
        Outer* parent;
      public:
        Inner1(Outer* p) : parent(p) {}
        void poing() {
          cout << "poing called for "
            << parent->name << endl;
          // Acesses data in the outer class object
        }
      } inner1;
    
      // Define a second inner class:
      class Inner2;
      friend class Outer::Inner2;
      class Inner2 : public Bingable {
        Outer* parent;
      public:
        Inner2(Outer* p) : parent(p) {}
        void bing() {
          cout << "bing called for "
            << parent->name << endl;
        }
      } inner2;
    public:
      Outer(const string& nm)
      : name(nm), inner1(this), inner2(this) {}
      // Return reference to interfaces
      // implemented by the inner classes:
      operator Poingable&() { return inner1; }
      operator Bingable&() { return inner2; }
    };
    
    int main() {
      Outer x("Ping Pong");
      // Like upcasting to multiple base types!:
      callPoing(x);
      callBing(x);
    } ///:~

    注意inner class的使用方法:1、前置声明 2、friend  3、定义 4、访问private变量

    内容源自:《TICPP-2nd-ed-Vol-two》

  • 相关阅读:
    iOS 6 Auto Layout NSLayoutConstraint 界面布局
    TexturePacker使用心得---1。
    今天说说敏捷个人-认识自我,管理自我 v0.2
    iPhone 5 屏幕尺寸变长指南
    JSON数据解析错误处理办法!
    IOS 入门介绍3iOS里面Frameworks介绍(续)
    Open GLSL ——01
    Open GLES 01
    IOS 入门介绍2iOS里面Frameworks介绍
    Opne GL ES 学习心得!
  • 原文地址:https://www.cnblogs.com/xkxjy/p/3679473.html
Copyright © 2011-2022 走看看