#include <iostream>
#include<string>
using namespace std;
class Animal
{
public:
virtual void cry()
{
cout<<"不知哪种动物,让我如何学叫?"<<endl;
}
};
class Mouse:public Animal
{
public:
//Mouse():name(0),sex(0) {};
Mouse(string name0,char sex0):name(name0),sex(sex0) {};
void cry();
private:
string name;
char sex;
}
void Mouse:: cry
if if(sex=='m')
cout<<"我叫"<<name<<","<<"是一只男老鼠,我的叫声是:吱吱吱!"<<endl;
else
cout<<"我叫"<<name<<","<<"是一只女老鼠,我的叫声是:吱吱吱!"<<endl;
}
class Cat:public Animal
{
public:
Cat(string name0):name(name0) {};
void cry();
private:
string name;
};
void Cat::cry()
{
cout<<"我叫"<<name<<","<<"是一只猫,我的叫声是:喵喵喵!"<<endl;
}
class dog:public Animal
{
public:
Dog(string name0):name(name0){};
void cry();
private:
string name;
};
void dog::cry()
{
cout<<"我叫"<<name<<","<<"是一只狗,我的叫声是:汪汪汪!"<<endl;
}
class Giraffe:public Animal
{
public:
//Mouse():name(0),sex(0) {};
Giraffe(string name0,char sex0):name(name0),sex(sex0) {};
void cry();
private:
string name;
char sex;
};
void Giraffe::cry()
{
if(sex=='m')
cout<<"我叫"<<name<<","<<"是一只男长颈鹿,我的脖子太长,发不出声音来!"<<endl;
else
cout<<"我叫"<<name<<","<<"是一只女长颈鹿,我的脖子太长,发不出声音来!"<<endl;
}
int main( )
{
Animal *p;
p = new Animal();
p->cry();
Mouse m1("Jerry",'m');
p=&m1;
p->cry();
Mouse m2("Jemmy",'f');
p=&m2;
p->cry();
Cat c1("Tom");
p=&c1;
p->cry();
Dog d1("Droopy");
p=&d1;
p->cry();
Giraffe g1("Gill",'m');
p=&g1;
p->cry();
return 0;
}
运行结果:
本文通过一个具体的C++程序示例介绍了多态性的概念及其在面向对象编程中的应用。通过不同类型的动物发出声音的行为展示了多态性的特点,使读者能够直观地理解并掌握这一重要的编程技巧。
3199

被折叠的 条评论
为什么被折叠?



