3.基类pet分别派生出Cat类和Dog类【问题描述】…
- User
3.基类pet分别派生出Cat类和Dog类【问题描述】 基类pet包含一个纯虚函数speak(),由pet类分别派生出Cat类和Dog类。Cat类扩展数据成员名字(字行串),成员函数speak函数输出“喵喵喵”,Dog类扩展数据成员名字(字符串),成员函数speak函数输出“汪注汪”。 参考主函数: int main(){ string name cin >> name Cat cc(name) cin >> name; Dog dd(name); Pet* pp; pp=&cc; pp->speak(); pp=ⅆ pp->speak(); return 0;} 写出完整的c++程序
- Assistant
#include #include using namespace std;
class Pet{ public: virtual void speak()=0;//纯虚函数,只有接口没有实体 };
class Cat: public Pet{ private: string name;//猫的名字 public: Cat(string n): name(n){} void speak(){//重载基类的函数 cout << "喵喵喵" << endl; } };
class Dog: public Pet{ private: string name;//狗的名字 public: Dog(string n): name(n){} void speak(){//重载基类的函数 cout << "汪汪汪" << endl; } };
int main(){ string name; cin >> name; Cat cc(name); cin >> name; Dog dd(name); Pet* pp; pp=&cc; pp->speak();//调用派生类Cat的函数 pp=ⅆ pp->speak();//调用派生类Dog的函数 return 0; }