定义一个基类 Animal,其中有一个虚函数 perform(),用于在子类中实现不同的表演行为。
#include <iostream>
using namespace std;
class Animal
{
public:
Animal() {}
virtual void perform()
{}
};
class Monkey:public Animal
{
public:
Monkey() {}
void perform()
{cout << "tiao" << endl;}
};
class elephlant:public Animal
{
public:
elephlant() {}
void perform()
{cout << "shuaibizi" << endl;}
};
class lion:public Animal
{
public:
lion() {}
void perform()
{cout << "hong" << endl;}
};
int main()
{
Animal *a;
Monkey m;
elephlant e;
lion l;
a=&m;
a->perform();
a=&e;
a->perform();
a=&l;
a->perform();
return 0;
}
用函数模板实现不同数据类型的交换功能。
#include <iostream>
#include<iomanip>
using namespace std;
template<typename T,typename Q>
void fun(T &a,Q &b)
{
T t=a;
a=static_cast<T>(b);
b=static_cast<Q>(t);
}
int main()
{
int a=10;
float b=2.5;
fun(a,b);
cout << a << setw(5) << fixed << setprecision(1) << b << endl;
return 0;
}