栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

侯捷C++面向对象高级编程之---(11-13)继承 & 复合 & 委托 & 虚函数与多态 & 委托相关设计

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

侯捷C++面向对象高级编程之---(11-13)继承 & 复合 & 委托 & 虚函数与多态 & 委托相关设计

参考详细帖子,包含实例-1

参考详细帖子,包含实例-2

Object Oriented Programming(OOP), Object Oriented Design (OOD)

Inheritance (继承),表示 is-a

  • struct也是一种class
  • 父类的成员,子类可以继承

    构造和析构
    - 构造:先父类(默认构造函数)后子类
    - 析构:先子类后父类析构函数
    - 父类析构必须时virtual,否则会出现undefined behavior
    - 编写class时,当该类可能会称为父类,就要把析构函数写成virtual(好习惯)
    -
    Inheritance (继承) with virtual


Composition(复合),表示 has-a

  • 复合 可以表示为 has-a 的关系,queue中有一个deque
  • 用图表示类之间的关系,实心的菱形
  • 传统c语言的struct也存在这种关系

    求sizeof

复合关系下的构造和析构

  • 构造由内而外
  • 析构由外而内
  • 不满意编译器调用默认构造函数,就要自己在同样的位置写清楚调用哪个。

    Delegation(委托)Composition by reference (其实就是pointer)
  • 相比上一个复合,委托是里面有一个其他类的指针(对应的对象和内存等到需要的时候才创建,不一定要在构造函数直接创建)
  • 图的话,用空心的菱形表示

委托相比复合:


补充一个弹幕的小问题:传参的时候,引用&和指针*的区别

  • &类似一个不能改变指向的地址,相当于 T* const,所以&是类型安全的,而*不是;
  • 可以用 const T* const 达到 const T&的目的 (没有T& const a这种形式)
  • &只能在定义时被初始化一次,之后不可变;*可变
  • &用.来调用,*用->来调用
  • *是一个实体,&仅仅是别名(不占内存)
  • &不能为空,*可以为空
  • sizeof中:&得到对应类型的大小,*得到指针的大小
  • 自增(++)运算意义不一样

继承 Inheritance + 复合 Composition 情况下的 构造和析构 的先后顺序

委托 Delegation + 继承 Inheritance :实例

设计模式的书:design pattern explained simply



delegation实例

注意:之所以说这个例子不好,因为虽然这里包含了类的指针,也即是委托。但是它并不是纯粹的pImpl模式,因为在sstring类里面还是包含了stringRep的成员,做这个例子只是为了实现count_n的功能而已,即表示多少sstring对象指向一个stringRep对象。

class stringRep
{
	friend class sstring;
public:
	stringRep() :count_n(0) { cout << "construct a objectStringRep" << endl; }
	~stringRep() { cout << "destruct a objectStringRep" << endl; }
	stringRep(const char* chr) :count_n(0) { this->chr = chr; cout << "construct a objectStringRep" << endl; }
	const char* getchr() const { return chr; }
	int get_n() const { return count_n; }
private:
	int count_n;
	const char* chr;
};


class sstring
{
public:
	sstring() { cout << "construct a objectString" << endl; }
	sstring(stringRep& sr) :rep(&sr) { sr.count_n++; cout << "construct a objectString" << endl; }
	~sstring() { (rep->count_n)--; cout << "destruct a objectString" << endl; }
private:
	stringRep* rep;
};


int main() {
	//delegation 实际应用

	stringRep sr("never give up!!!");
	sstring str1(sr);
	sstring str2(sr);
	sstring str3(sr);
	cout << endl << "count_n=" << sr.get_n() << endl ;
	cout << sr.getchr() << endl;
	return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/302941.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号