定义一个基类 Animal,其中有一个虚函数 perform(),用于在子类中实现不同的表演行为。
#include <iostream>
using namespace std;
//封装 Animal 类 ---》基类
class Animal
{
private:
string name;
public:
//无参
Animal()
{}
//有参
Animal(string n):name(n)
{
cout << "Aminal的有参构造函数" << endl;
}
virtual void perform() = 0;
};
//封装 狮子 类 继承于Aminal 类
class Lion :public Animal
{
private:
string skill;
public:
//无参
Lion()
{}
//有参构造
Lion(string n, string s):Animal(n),skill(s)
{
cout << "Lion的有参构造函数" << endl;
}
void perform()
{
cout << "Lion跳跃" << endl;
}
};
//封装 猴子 类 继承于Aminal 类
class Monkey: public Animal
{
private:
int age;
public:
//无参
Monkey()
{}
//有参构造
Monkey(string n, int a):Animal(n),age(a)
{
cout << "Monkey的有参构造函数" << endl;
}
void perform()
{
cout << "Monkey花式篮球" << endl;
}
};
int main()
{
Animal *p; //父类的指针
Lion L("yy","Jump");
p = &L;
p->perform();
Monkey M("vv", 12);
p = &M;
p->perform();
return 0;
}
2.用函数模板实现不同数据类型的交换功能。
#include <iostream>
using namespace std;
template <typename T>
void fun(T &a, T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}
int main()
{
int a = 10, b = 20;
fun(a, b);
cout << a << " " << b << endl;
double c = 1.3, d = 1.4;
fun(c, d);
cout << c << " " << d << endl;
return 0;
}
3 思维导图