the “inner class” idiom
2024-08-24 19:42:42
有些时候我们需要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() = ;
};
void callPoing(Poingable& p) {
p.poing();
} class Bingable {
public:
virtual void bing() = ;
};
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》
最新文章
- 图片在保存的时候===》出现这个异常:GDI+ 中发生一般性错误
- 解析opencv中Box Filter的实现并提出进一步加速的方案(源码共享)。
- 《learning hard C#学习笔记》读书笔记(19)多线程
- YbSoftwareFactory 代码生成插件【十七】:先进的权限模型体系设计
- OC中用NSSortDescriptor对象进行数组排序
- IEnumerable 遍历用法
- return exit _exit
- 用php做了下冒泡排序
- zabbix企业级监控概述和部署
- CocoaPods requires your terminal to be using UTF-8 encoding
- mac 下 配置 阿帕奇
- kubernetes in action - Volumes
- (逆序对 分治法)P1908 逆序对 洛谷
- $Django cbv源码分析 djangorestframework框架之APIView源码分析
- SpringMVC国际化与文件上传
- LOJ10155数字转换
- ps怎么撤销的三种方法和ps撤销快捷键以及连续撤销多步快捷键
- pyhanlp 共性分析与短语提取内容详解
- MFC使用自定义资源加载PNG
- [Java学习] Java继承的概念与实现