# 多态

### 多态性总结

#### 类型举例

###### 1.重载多态

{

}

{

}

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 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;
}


###### 4.参数多态

template <class 数据类型参数标示符>

{

}

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