1.定义一个animal基类,其中有perform虚函数,用于在子类中实现不同的表演行为
#include <iostream>
using namespace std;
//定义一个动物 基类
class Animal
{
private:
string name;
public:
//无参函数
Animal(){}
//有参函数
Animal(string n):name(n)
{}
virtual void perform()
{
cout << "动物园里有什么" << endl;
}
};
//定义一个 狮子类 继承于动物类
class Lion:public Animal
{
private:
int high;
public:
//无参构造
Lion(){}
//有参构造
Lion(string n,int h):Animal(n),high(h)
{}
void perform()
{
cout << "狮子表演跳舞" << endl;
}
};
//定义一个 大象类 继承于动物类
class Elephant:public Animal
{
private:
int weight;
public:
//无参构造
Elephant(){}
//有参构造
Elephant(string n,int w):Animal(n),weight(w)
{}
void perform()
{
cout << "大象表演喝水" << endl;
}
};
//定义一个 猴子类 继承于动物类
class Monkey:public Animal
{
private:
string sex;
public:
//无参函数
Monkey(){}
//有参构造
Monkey(string n,string s):Animal(n),sex(s)
{}
void perform()
{
cout << "猴子表演跳绳" << endl;
}
};
int main()
{
cout << "大家一起来看表演" << endl;
Lion l("狮子",200);
Animal *p;
p = &l;
p->perform();
Elephant e("大象",1000);
p = &e;
p->perform();
Monkey m("猴子","雌性");
p = &m;
p->perform();
return 0;
}
2.用函数模板实现不同类型数据的交换功能
#include <iostream>
using namespace std;
template <typename T,typename B>
void fun(T &a,B &b)
{
B temp;
temp = a;
a = b;
b = temp;
}
int main()
{
int a = 10;
char b = 'a';
cout << a << " " << b << endl;
fun(a,b);
cout << (char)a << " " << (int)b << endl;
return 0;
}