/*多态:一种接口,多种方法,即将运算符、函数重载,实现不同的功能
1、编译时多态:编译器进行编译时就可以确定调用的是哪个函数。通过重载实现
2、运行时多态:在程序运行过程中根据实际情况来确定调用的哪个函数。通过虚函数来实现
*/
//编译时多态
#include<iostream>
using namespace std;
char max_(char a, char b) { return a > b ? a : b; };
int max_(int a, int b) { return a > b ? a : b; };
float max_(float a, float b) { return a > b ? a : b; };
int main() {
float a = 2.15, b = 3.14;
cout << max_('x','u') << endl;
cout << max_(2,8) << endl;
//cout << max_(2.15,5.14) << endl; //浮点型要先定义,直接这样写会报错
cout << max_(a, b) << endl;
return 0;
}
//运行时多态。
#include<iostream>
using namespace std;
class Pet { //基类
public:
virtual void sing() { //virtual关键字,基类中函数前面加virtual关键字表示这是一个虚函数
cout << "emmmmm" << endl;
}
};
class Cat :public Pet { //公有继承
public:
void sing() {
cout << "miao~~~" << endl;
}
};
class Dog :public Pet {
public:
void sing(){
cout << "wang~~~" << endl;
}
};
int main() {
Pet pet;
Pet* p = &pet;
Cat cat;
Dog dog;
int a;
cin >> a;
if (a == 1) p = &cat;
if (a == 2) p = &dog;
p->sing();
//输入1,则输出miao~~~;输入2,则输出wang~~~;输入其他数,则输出emmmmm
return 0;
}
基类对象与派生类对象的替换:
//基类对象与派生类对象的替换,三种方法
#include<iostream>
using namespace std;
class H {
public:
void who() {
cout << "human" << endl;
}
};
class M :public H{
public:
void who(){
cout << "man" << endl;
}
};
class W :public H {
public:
void who() {
cout << "woman" << endl;
}
};
int main() {
H h, * p1;
M m;
W w;
h = m;//将派生类对象赋值给基类对象
h.who();//输出human
p1 = &m;//将派生类对象地址赋给基类指针
p1->who();//输出human
H& p2 = w; //派生类对象初始化基类对象的引用
p2.who();//输出human
return 0;
}