C++多态(虚函数)使用详解

目录

1.什么是多态

1.1父类指针指向子类指针案例

2.多态—虚函数的基本使用

3.多态——虚函数表

3.1单个类的虚函数表

3.2使用继承的虚函数表

3.3多重继承的虚函数表

4.虚函数的修饰

4.1虚函数的修饰——final

4.2虚函数的修饰——override

5.遗失的子类析构函数

6.纯虚函数与抽象类

6.1什么时候使用纯虚函数

6.2纯虚函数使用方法

6.3纯虚函数注意事项


1.什么是多态

多态的本质:

形式上,使用统一的父类指针做一般性处理

但是实际执行时,这个指针可能指向子类对象,

形式上,原本调用父类的方法,但是实际上会调用子类的同名方法

1.1父类指针指向子类指针案例

#include <iostream>
using namespace std;

class Father {
public:
	void play() {
		cout << "到KTV唱歌..." << endl;
	}
};

class Son :public Father {
public:
	void play() {
		cout << "一起打王者吧!" << endl;
	}
};

void party(Father** men, int n) {
	for (int i = 0; i < n; i++) {
		men[i]->play();
	}
}
int main(void) {
	Father father;
	Son son1, son2;
	Father* men[] = { &father, &son1, &son2 };

	party(men, sizeof(men) / sizeof(men[0]));

	system("pause");
	return 0;
}

 运行截图:

 解决方案:

通过虚函数,实现多态。在父类中将与子类重名的函数前加上virtual

class Father {
public:
	virtual void play() {
		cout << "到KTV唱歌..." << endl;
	}
};

 运行截图:

 2.多态—虚函数的基本使用

虚函数的定义:

在函数的返回类型之前使用virtual

只在成员函数的声明中添加virtual, 在成员函数的实现中不要加virtual

虚函数的继承:

  1. 如果某个成员函数被声明为虚函数,那么它的子类【派生类】,以及子类的子类中,所继承的这个成员函数,也自动是虚函数。
  2. 如果在子类中重写这个虚函数,可以不用再写virtual, 但是仍建议写virtual, 更可读!

3.多态——虚函数表

3.1单个类的虚函数表

对象内,首先存储的是“虚函数表指针”,又称“虚表指针”。

然后再存储非静态数据成员。

对象的非虚函数,保存在类的代码中!

对象的内存,只存储虚函数表数据成员

(类的静态数据成员,保存在数据区中,和对象是分开存储的)

添加虚函数后,对象的内存空间不变!仅虚函数表中添加条目

多个对象,共享同一个虚函数表!

手绘内存分布:

代码示例: 

#include <iostream>
using namespace std;

class Father {
public:
	virtual void func1() { cout << "Father::func1" << endl; }
	virtual void func2() { cout << "Father::func2" << endl; }
	virtual void func3() { cout << "Father::func3" << endl; }
	void func4() { cout << "非虚函数:Father::func4" << endl; }
public:  //为了便于测试,特别该用public
	int x = 100;
	int y = 200;
	static int z;
};

typedef void (*func_t)(void);
int Father::z = 1;
int main(void) {
	Father father;

	// 含有虚函数的对象的内存中,最先存储的就是“虚函数表”
	cout << "对象地址:" << (int*)&father << endl;

	int* vptr = (int*)*(int*)&father;
	cout << "虚函数表指针vptr:" << vptr << endl;

	cout << "调用第1个虚函数: ";
	((func_t) * (vptr + 0))();

	cout << "调用第2个虚函数:";
	((func_t) * (vptr + 1))();

	cout << "调用第3个虚函数: ";
	((func_t) * (vptr + 2))();


	cout << "第1个数据成员的地址: " << endl;
	cout << &father.x << endl;
	cout << std::hex << (int)&father + 4 << endl;
	cout << "第1个数据成员的值:" << endl;
	cout << std::dec << father.x << endl;
	cout << *(int*)((int)&father + 4) << endl;

	cout << "第2个数据成员的地址: " << endl;
	cout << &father.y << endl;
	cout << std::hex << (int)&father + 8 << endl;
	cout << "第2个数据成员的值:" << endl;
	cout << std::dec << father.y << endl;
	cout << *(int*)((int)&father + 8) << endl;

	cout << "sizeof(father)==" << sizeof(father) << endl;

	Father father2;
	cout << "father的虚函数表:";
	cout << *(int*)(*(int*)&father) << endl;
	cout << "father2的虚函数表:";
	cout << *(int*)(*(int*)&father2) << endl;

	system("pause");
	return 0;
}

 运行截图:

或者可以使用VS的对象内存分布分析:

项目的命令行配置中添加: /d1 reportSingleClassLayoutFather

 编译结果:

3.2使用继承的虚函数表

#include <iostream>
using namespace std;

class Father {
public:
	virtual void func1() { cout << "Father::func1" << endl; }
	virtual void func2() { cout << "Father::func2" << endl; }
	virtual void func3() { cout << "Father::func3" << endl; }
	void func4() { cout << "非虚函数:Father::func4" << endl; }
public:  //为了便于测试,特别该用public
	int x = 100;
	int y = 200;
};

class Son : public Father {
public:
    //子类重写虚函数可以不写virtual,也可以写
	void func1() { cout << "Son::func1" << endl; }
	virtual void func5() { cout << "Son::func5" << endl; }
};

内存分布:

 子类虚函数表构建补充

3.3多重继承的虚函数表

#include <iostream>

using namespace std;

class Father {
public:
	virtual void func1() { cout << "Father::func1" << endl; }
	virtual void func2() { cout << "Father::func2" << endl; }
	virtual void func3() { cout << "Father::func3" << endl; }
	void func4() { cout << "非虚函数:Father::func4" << endl; }
public:
	int x = 200;
	int y = 300;
	static int z;
};

class Mother {
public:
	virtual void handle1() { cout << "Mother::handle1" << endl; }
	virtual void handle2() { cout << "Mother::handle2" << endl; }
	virtual void handle3() { cout << "Mother::handle3" << endl; }
public: //为了便于测试,使用public权限
	int m = 400;
	int n = 500;
};

class Son : public Father, public Mother {
public:
	void func1() { cout << "Son::func1" << endl; }
	virtual void handle1() { cout << "Son::handle1" << endl; }
	virtual void func5() { cout << "Son::func5" << endl; }
};

 内存分布:

VS编译分析:

 

4.虚函数的修饰

4.1虚函数的修饰——final

1.用来修饰类,让该类不能被继承

理解:使得该类终结!

class XiaoMi {
public:
	XiaoMi(){}
};

//继承方式如果不写默认是private
class XiaoMi2 final : public XiaoMi  {
	XiaoMi2(){}
};

class XiaoMi3 : public XiaoMi2 {  //不能把XiaoMi2作为基类

};

class Phone8848 final{    //这个类将不能被继承

}

 2.用来修饰类的虚函数,使得该虚函数在子类中,不能被重写但是可以使用

理解:使得该功能终结!

class XiaoMi {
public:
	virtual void func() final;
};

void XiaoMi::func() { //不需要再写final
	cout << "XiaoMi::func" << endl; 
}

class XiaoMi2 : public XiaoMi  {
public:
	void func() {}; // 错误!不能重写func函数     但是派生类可以使用
};

4.2虚函数的修饰——override

 override仅能用于修饰虚函数。

作用:

     1.提示程序的阅读者,这个函数是重写父类的功能。

     2.防止程序员在重写父类的函数时,把函数名写错。

#include <iostream>
using namespace std;

class XiaoMi {
public:
	virtual void func() { cout << "XiaoMi::func" << endl; };
};

class XiaoMi2 : public XiaoMi  {
public:
	void func() override {}
	//void func() override;  告诉程序员func是重写父类的虚函数
	//void func1() override{} 错误!因为父类没有func1这个虚函数
};

提醒程序员,防止在重写父类虚函数时,把函数名写错

 override只需在函数声明中使用,不需要在函数的实现中使用。

 5.遗失的子类析构函数

当父类指针指向子类时,使用delete会出现子类析构函数不自动调用

#include <iostream>
#include <Windows.h>
#include <string.h>

using namespace std;

class Father {
public:
	Father(const char* addr = "中国") {
		cout << "执行了Father的构造函数" << endl;
		int len = strlen(addr) + 1;
		this->addr = new char[len];
		strcpy_s(this->addr, len, addr);
	}

	 ~Father() {
		cout << "执行了Father的析构函数" << endl;
		if (addr) {
			delete addr;
			addr = NULL;
		}
	}
private:
	char* addr;
};

class Son :public Father {
public:
	Son(const char* game = "吃鸡", const char* addr = "中国")
		:Father(addr) {
		cout << "执行了Son的构造函数" << endl;
		int len = strlen(game) + 1;
		this->game = new char[len];
		strcpy_s(this->game, len, game);
	}
	~Son() {
		cout << "执行了Son的析构函数" << endl;
		if (game) {
			delete game;
			game = NULL;
		}
	}
private:
	char* game;
};

int main(void) {
	cout << "----- case 1 -----" << endl;
	Father* father = new Father();
	delete father;

	cout << "----- case 2 -----" << endl;
	Son* son = new Son();
	delete son;

	cout << "----- case 3 -----" << endl;
	father = new Son();
	delete father;

	system("pause");
	return 0;
}

 运行截图:

解决方案:将父类析构函数定义为virtual函数

 把Father类的析构函数定义为virtual函数时,

如果对 Father类的指针使用delete操作时,

 就会对该指针使用“动态析构”:

如果这个指针,指向的是子类对象,

那么会先调用该子类的析构函数,再调用自己类的析构函数

 修改父类代码:

virtual ~Father() {
		cout << "执行了Father的析构函数" << endl;
		if (addr) {
			delete addr;
			addr = NULL;
		}
	}

 执行结果:

6.纯虚函数与抽象类

6.1什么时候使用纯虚函数

某些类,在现实角度和项目实现角度,都不需要实例化(不需要创建它的对象),

这个类中定义的某些成员函数,只是为了提供一个形式上的接口,准备让子类来做具体的实现。

此时,这个方法,就可以定义为“纯虚函数”, 包含纯虚函数的类,就称为抽象类。

6.2纯虚函数使用方法

用法:纯虚函数,使用virtual和 =0

 代码示例:

#include <iostream>
#include <string>

using namespace std;

class Shape {
public:
	Shape(const string& color = "white") { this->color = color; }
	virtual float area() = 0; //不用做具体的实现
	string getColor() { return color; }
private:
	string color;
};

class Circle : public Shape {
public:
	Circle(float radius = 0, const string& color = "White")
		:Shape(color), r(radius) {}
	float area();
private:
	float r; //半径
};


float Circle::area() {
	return 3.14 * r * r;
}



int main() {
	//使用抽象类创建对象非法!
	//Shape s;  

	Circle c1(10);
	cout << c1.area() << endl;

	Shape* p = &c1;
	cout << p->area() << endl;

	system("pause");
	return 0;
}

6.3纯虚函数注意事项

父类声明某纯虚函数后,

那么它的子类,

  1. 要么实现这个纯虚函数 (最常见)
  2. 要么继续把这个纯虚函数声明为纯虚函数,这个子类也成为抽象类
  3. 要么不对这个纯虚函数做任何处理,等效于上一种情况(该方式不推荐)


 

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值