理清虚继承、多态、虚函数

虚继承

  • 使用虚继承时,通过virtual关键字修饰继承关系,虚继承中的父类为虚基类
  • 虚继承避免了访问的二义问题
class A{
public:
	char c1;
	A(){c1 = 'A';}
	A(char c1){this->c1 = c1;}
};

class B:public virtual A{
public:	
	char c2;
	B(){c2 ='B';}
	B(char c1,char c2):A(c1){this->c2 = c2;}
};

class C:public virtual A{
public:
	char c3;
	C(){c3 = 'C';}
	C(char c1,char c3):A(c1){this->c3 = c3;}
};

class D:public B,public C{
public:
	char c4;
	D(){c4 = 'D';}
	D(char c1,char c2,char c3,char c4):B(c1,c2),C(c3,c3){this->c4 = c4;}
};

D dd('a','b','c','d');
cout<<dd.c1<<dd.c2<<dd.c3<<dd.c4<<endl;

输出结果:

Abcd

菱形继承关系

A
B
C
D
  • 在菱形继承中,底层类的构造函数初始化列表中会首先调用顶层类的构造函数
  • 虚继承保证继承关系中的虚基类只被初始化一次,类A的构造函数不会被执行两次

多态

多态指不同对象对于同样的消息做出不同的响应
多态通过虚函数实现

class Base{
public:
	virtual void f1(){cout<<"base::f1()"<<endl;} //虚函数
	void f2(){cout<<"base::f2()"<<endl;}
};

class Derived:public Base{
public:
	void f1(){cout<<"Derived::f1()"<<endl;}
	void f2(){cout<<"Derived::f2()"<<endl;}
};
Base * b = new Derived();
b->f1();
b->f2();

输出结果

Derived::f1()
base::f2()

纯虚函数

  • 纯虚函数不会给出具体实现
  • 含有纯虚函数的类称为抽象类,抽象类不能创建对象,只能作为父类使用
class Shape{
protected:
	float x;
	float y;
public:
	Shape(float i,float j):x(i),y(j){}
	virtual void printArea() = 0; //纯虚函数
};

class Rect:public Shape{ //矩形面积
public:
	Rect(float i,float j):Shape(i,j){}
	void printArea(){cout<<"Rect:"<<x*y<<endl;}
};

class Tria:public Shape{  //三角形面积
public:
	Tria(float i,float j):Shape(i,j){}
	void printArea(){cout<<"Tria:"<<x*y/2 <<endl;}
};

你可能感兴趣的:(理清虚继承、多态、虚函数)