一、定义基类Animals,以及多个派生类,基类中至少包含虚函数perform()
#include <iostream>
using namespace std;
class Aniamls
{
private:
string cry;
public:
Aniamls() {}
Aniamls(string cry):cry(cry) {}
virtual void perform() = 0; //纯虚函数
};
class Cat:public Aniamls
{
private:
string c_cry;
public:
Cat() {}
Cat(string c_cry,string cry):Aniamls(cry),c_cry(c_cry) {}
void perform()
{
cout << "喵喵喵..." << endl;
}
};
class Dog:public Aniamls
{
private:
string d_cry;
public:
Dog() {}
Dog(string d_cry,string cry):Aniamls(cry),d_cry(d_cry) {}
void perform()
{
cout << "汪汪汪..." << endl;
}
};
int main()
{
Cat c;
Dog d;
Aniamls *p;
p = &c;
p->perform();
p = &d;
p->perform();
return 0;
}
二、用函数模型实现不同数据类型的交换功能
#include <iostream>
#include <iomanip>
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 << setw(5) << b << endl;
double c = 1.2,d = 2.5;
fun(c,d);
cout << c << setw(5) << d << endl;
return 0;
}
文章来源地址https://www.toymoban.com/news/detail-680937.html
文章来源:https://www.toymoban.com/news/detail-680937.html
到了这里,关于C++,多态练习的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!