📄 vc0903.cpp
字号:
// Example 9.3: 抽象宠物类
#include <iostream.h>
#include <string.h>
class Pet //基类
{
char m_strName[20];
int m_nAge;
char m_strColor[12];
public:
char m_strType[10];
Pet(char *,int ,char *);
char* GetName() { return m_strName; }
int GetAge() { return m_nAge; }
char* GetColor() { return m_strColor; }
virtual void Speak() = 0;
virtual void GetInfo() {}
};
Pet::Pet(char *name,int age,char *color)
{
strcpy(m_strName,name);
m_nAge=age;
strcpy(m_strColor,color);
strcpy(m_strType,"pet");
}
class Cat : public Pet //派生类
{
public:
Cat(char *name,int age, char *color):Pet(name,age,color)
{ }
void Speak()
{ cout<<" Sound of speak : miao!miao!"<<endl<<endl; }
void GetInfo();
};
void Cat::GetInfo()
{
cout<<" The cat's name : "<<GetName()<<endl;
cout<<" The cat's age : "<<GetAge() <<endl;
cout<<" The cat's color: "<<GetColor()<<endl;
}
class Dog : public Pet //派生类
{
public:
Dog(char *name,int age, char *color):Pet(name,age,color)
{ }
void Speak()
{ cout<<" Sound of speak : wang!wang!"<<endl<<endl; }
void GetInfo();
};
void Dog::GetInfo()
{
cout<<" The dog's name : "<<GetName()<<endl;
cout<<" The dog's age : "<<GetAge() <<endl;
cout<<" The dog's color: "<<GetColor()<<endl;
}
void main()
{
Pet *p1; //基类对象指针p1
p1 = new Cat("MiKey",1,"Blue"); //动态生成Cat类对象
p1->GetInfo();
p1->Speak();
delete p1;
p1 = new Dog("BenBen",2,"Black");//动态生成Dog类对象
p1->GetInfo();
p1->Speak();
delete p1;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -