- 1
- 0
- 约2.28万字
- 约 69页
- 2021-11-30 发布于安徽
- 举报
C++ object layout Outline Introduction Virtual functions Abstract vs. concrete Polymorphism Using of polymorphism Early vs. late C++ object layout Virtual inheritance Virtual Base Class 虚基类(Virtual Base Class)解决了什么问题——多重继承的二义性。 1 class A { 2 public: 3 void set( int m ) { this-m = m ; } int get() const { return this-m ; } ; private: int m ; 5 } ; 6 class B : public A { } ; 7 Class C : public A { } ; 8 Class D : public B, public C { } ; B继承了A,继承了数据成员m C继承了A,继承了数据成员m D继承了B和C,继承了两个数据成员m? Virtual Base Class 1 D d ; 2 d.set( 23 ) ; //Error: request for member set is ambiguous 3 std::cout d.get() ; //Error: request for member set is ambiguous 使用虚基类正是为了在多重继承的类层次中节省空间 和避免不确定性。 派生类D拥有两个数据成员m。这在浪费空间的同时, 产生了数据访问的不确定性。 以上代码在编译时会报错: 虚基类(Virtual Base Class)格式如下: virtual 继承方式基类名 1 class A { 2 public: 3 void set( int m ) { this-m = m ; } int get() const { return this-m ; } ; private: int m ; 5 } ; 6 class B : virtual public A { } ; 7 Class C : virtual public A { } ; 8 Class D : virtual public B, virtual public C { } ; D继承了B和C,但是只继承了一个数据成员m Virtual Base Class 虚基类是相对于它的派生类而言的,它本身可以是一个普通的类。 只有它的派生类虚继承它的时候,它才称作虚基类,如果没有虚继承的话,就称为基类。 Virtual Base Class How to express Virtual in UML diagrams pure virtual function = abstract method class with pure virtual function = abstract class virtual function will be recognize when a method has been overridden be careful when override one of overloaded virtual functions since all other functions with the same name will be hidden Thank you! * * * * * * * Virtual Destructors 最佳实践 (best practice): 即使析构函数没有工作要做,继承层次的根类也应该定义一个虚析构函数。 构造函数和赋值操作符不能是虚函数 构造函数是在对象完全构造之前运行的,在构造函数运行的时候,对象的动态类型还不完整。 每个类有自己的赋值操作符,派生类中的赋值操作符有一个与类本身类型相同的形参。将赋值操作符设为虚函数可能会出错,因为虚函数必须在基类和派生类中具有同样的形参。 Case Study: Inheriting Interface and Implementation Re-examine the Point, Circle, Cylinder hierarchy Use the abstract base class Shape to head the hierarchy Shape Definition (abstract base class) --------------------- 1. Point Definition (derived class) 1
原创力文档

文档评论(0)