zoukankan      html  css  js  c++  java
  • 抽象宠物类的实现 代码参考

     1 #include <iostream>
     2 #include <string>
     3 
     4 using namespace std;
     5 
     6 class Pet
     7 {
     8     private:
     9         string name;
    10         int age;
    11         string color;
    12     public:
    13         Pet(string name,int age,string color)
    14         {
    15             this->name=name;
    16             this->age=age;
    17             this->color=color;
    18         }
    19         string Getname(){return name;}
    20         int Getage(){return age;}
    21         string Getcolor(){return color;}
    22         virtual void Speak();
    23         virtual void Getinfo();
    24 };
    25 
    26 void Pet::Speak()
    27 {
    28     cout<<"How does a pet speak?"<<endl;
    29     return;
    30 }
    31 
    32 void Pet::Getinfo()
    33 {
    34     cout<<"名字:"<<name<<endl;
    35     cout<<"年龄:"<<age<<endl;
    36     cout<<"颜色:"<<color<<endl;
    37 }
    38 
    39 class Cat:public Pet
    40 {
    41     public:
    42         Cat(string name, int age, string color):Pet(name,age,color){}
    43         void Speak();
    44         void Getinfo();
    45 };
    46 
    47 void Cat::Speak()
    48 {
    49     cout<<"猫的叫声:miao!miao!"<<endl;
    50     return;
    51 }
    52 
    53 void Cat::Getinfo()
    54 {
    55     cout<<"猫的名字:"<<Getname()<<endl;
    56     cout<<"猫的年龄:"<<Getage()<<endl;
    57     cout<<"猫的颜色:"<<Getcolor()<<endl;
    58     return;
    59 }
    60 
    61 class Dog:public Pet
    62 {
    63     public:
    64         Dog(string name, int age, string color):Pet(name,age,color){}
    65         void Speak();
    66         void Getinfo();
    67 };
    68 
    69 void Dog::Speak()
    70 {
    71     cout<<"狗的叫声:wang!wang!"<<endl;
    72     return;
    73 }
    74 
    75 void Dog::Getinfo()
    76 {
    77     cout<<"狗的名字:"<<Getname()<<endl;
    78     cout<<"狗的年龄:"<<Getage()<<endl;
    79     cout<<"狗的颜色:"<<Getcolor()<<endl;
    80     return;
    81 }
    82 
    83 int main()
    84 {
    85     string name1,name2,color1,color2;
    86     int age1,age2;
    87     cin>>name1>>age1>>color1;
    88     cin>>name2>>age2>>color2;
    89     Pet *p1,*p2;
    90     p1=new Cat(name1,age1,color1);
    91     p2=new Dog(name2,age2,color2);
    92     p1->Getinfo();
    93     p1->Speak();
    94     p2->Getinfo();
    95     p2->Speak();
    96     return 0;
    97 }
  • 相关阅读:
    双写一致性的讨论
    webstorm设置新建vue文件的模板
    java基础类及方法
    中国大学零基础学Java语言练习题
    java基础继承
    java基础接口、继承、多态
    Windows、Mac 命令行启动程序(为了查看Electron打包后主进程日志)
    【Typescirpt】定义数字范围类型
    MRP
    Raid 学习
  • 原文地址:https://www.cnblogs.com/Conan-jine/p/12799324.html
Copyright © 2011-2022 走看看