多态

多态性总结

多态性概述

多态是指同样的消息被不同类型的对象接收时导致不同的行为。

多态类型

在这里插入图片描述

类型举例

1.重载多态

运算符重载:是对已有的运算符赋予多重含义,使同一个运算符作用于不同类型的数据时导致不同的行为

运算符重载为类的成员函数:
返回类型 operator 运算符(形参表)
{
函数体
}
运算符重载为非成员函数:
返回类型 operator 运算符(形参表)
{
函数体
}

operator是定义运算符重载函数的关键字。

将单目运算符“++”重载为成员函数:

#include<iostream>
using namespace std;

class clock {
private:
	int hour, minute, second;
public:
	clock(int hour=0,int minute=0,int second=0);
	void showTime() const;
	clock& operator++();//前置
	clock operator++(int);//后置
};
clock::clock(int hour, int minute, int second) {
	if (0 <= hour && hour < 24 && 0 <= minute && minute < 60 && 0 <= second && second < 60)
	{
		this->hour = hour;
		this->minute = minute;
		this->second = second;
	}
	else
		cout << "Time Error!" << endl;
}
void clock::showTime()const {
	cout << hour << ":" << minute << ":" << second << endl;
}
clock& clock::operator++() {
	second++;
	if (second >= 60) {
		second -= 60;
		minute++;
		if (minute >= 60) {
			minute -= 60;
			hour = (hour + 1) % 24;
		}
	}
	return *this;
}
clock clock::operator++(int) {
	clock old = *this;
	++(*this);
	return old;
}

int main()
{
	clock c(23, 59, 59);
	cout << "First time:";
	c.showTime();
	cout << "show c++:  ";
	(c++).showTime();
	cout << "show ++c:  ";
	(++c).showTime();
	return 0;
}

运行结果:
在这里插入图片描述
重载为非成员函数

#include<iostream>
using namespace std;

class p {
private:
	int x, y;
public:
	p(int x=0,int y=0):x(x),y(y){}
	void show();
	friend p& operator++(p &c1);
	friend p operator++(p &c1, int);
};

p& operator++(p &c1) {
	++c1.x;
	++c1.y;
	return c1;
}
p operator++(p &c1, int) {
	p old = c1;
	++c1;
	return old;
}

void p::show()
{
	cout << "("<< x << "," << y << ")" << endl;
}

int main()
{
	p a, b, c;
	c = a++;
	c.show();
	c = ++b;
	c.show();
	return 0;
}

运行结果;
在这里插入图片描述

2.强制多态

强制多态:编译程序通过语义操作,把操作对象的类型强行加以变换,以符合函数或操作符的要求。程序设计语言中基本类型的大多数操作符,在发生不同类型的数据进行混合运算时,编译程序一般都会进行强制多态。程序员也可以显示地进行强制多态的操作。举个例子,比如,int+double,编译系统一般会把int转换为double,然后执行double+double运算,这个int-》double的转换,就实现了强制多态,即可是隐式的,也可显式转换。

举个例子:

int a=1;
float b=2.2f;
float c=a+b;
3.包含多态

是类族中定义于不同类中的同名成员函数的多态行为,主要通过虚函数实现。
基类中包含虚函数,并且派生类中一定要对基类中的虚函数进行重写。
通过基类对象的指针或者引用调用虚函数

#include<iostream>
using namespace std;

class Mammal {
public:
	virtual void speak();
};
void Mammal::speak()
{
	cout << "Mammal::speak()" << endl;
}
class Dog :public Mammal {
public:
	void speak();

};
void Dog::speak()
{
	cout << "Dog::speak()" << endl;
}

void fun(Mammal *p)
{
	p->speak();
}

int main()
{
	Dog a;
	fun(&a);

	return 0;
}

在这里插入图片描述

将speak()定义为virtual,之后再通过fun()函数调用。
用fun函数可以有效避免代码重复,提高了效率,增强了简洁性。

4.参数多态

采用函数模板,它可以用来创建一个通用的函数,以支持多种不同形参,避免重载函数的函数体重复设计,通过给出不同的类型参数,使得一个结构有多种类型。

定义的一般形式:
template <class 数据类型参数标示符>
函数返回值类型 函数名(参数表)
{
函数体
}

posted @ 2019-10-27 11:25  七岁就很酷  阅读(139)  评论(0编辑  收藏  举报