C++编程思想 第2卷 第10章 设计模式 观察者模式 内部类方法

在某些情况下
必须有效地向上类型转换 upcast 成为多个不同的类型
但是在这种情况下
需要为同一个基类型提供几个不同的实现

在C++中实现内部类 inner class方法
必须显式获得和使用指向包含指向包含对象的指针

//: C10:InnerClassIdiom.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// 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;
      // Accesses 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);
  getchar();
} ///:~

输出
poing called for Ping Pong
bing called for Ping Pong

这个例子以接口Poingable和Bingable开始
每个接口包含一个成员函数
由callPoing()和callBing()提供的服务要它们接收的对象分别实现
对应的Poingable和Bingable接口
除此之外 对 对象没有别的请求

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/82622361