bear七 2022-05-10 11:09 采纳率: 83.3%
浏览 31
已结题

C++代码相关问题继承与派生


#include<iostream>
using namespace std;
class Animal{
 protected:
  unsigned int Age;double Weight;string Name;
 public:
  Animal(unsigned int age,double weight,string name)
  {
   Age=age;
   Weight=weight; 
   Name=name;
      cout << "Animal Constructor" << endl;
  }
  Animal()
  {
   cout << "Animal Constructor" << endl;
  }
};
class Fish:virtual public Animal{
 protected:
  bool Fim;
 public:
  Fish(unsigned int age,double weight,string name,bool Fim):Animal(age,weight,name)
  {
   this->Fim=Fim;
       cout << "Fish Constructor" << endl;
  }
  Fish()
  {
     cout << "Fish Constructor" << endl;
  }
};
class TerrestrialAnimal:virtual public Animal{
 protected:
  unsigned int Legs;
 public:
  TerrestrialAnimal(unsigned int age,double weight,string name,unsigned Leg):Animal(age,weight,name)
  {
   Legs=Leg;
      cout << "TerrestrialAnimal Constructor" << endl;
  }
  TerrestrialAnimal()
  {
   cout << "TerrestrialAnimal Constructor" << endl;
  }
};

class Reptile:public Fish,public TerrestrialAnimal{
 public:
  Reptile(unsigned int age,double weight,string name,unsigned int Leg,bool Fim):Animal(age,weight,name),Fish(age,weight,name,Fim),TerrestrialAnimal(age,weight,name,Leg)
  {cout << "Reptile Constructor" << endl;}
 Reptile()
 {
  cout << "Reptile Constructor" << endl;
 } 
 void Print()
 {
        cout << "Reptile Age:" << Age << endl;
    }
};
int main(){
    int age;
    int weight;
    string name;
    int fim_num;
    int leg_num;
    cin >> age >> weight >> name >> fim_num >> leg_num;
    Reptile r1(age, weight, name, fim_num, leg_num);
    r1.Print();
    return 0;
}
  

要求TerrestrialAnimal Constructor输出顺序在Fish Constructor的前面。主函数不变,请问怎么修改代码,谢谢!

  • 写回答

2条回答 默认 最新

  • SmallAntJ 2022-05-10 11:41
    关注

    把49行继承顺序调换一下:

    class Reptile:public TerrestrialAnimal, public Fish
    

    多重继承判断构造顺序要看继承的关系,虚基类先构造,然后是普通基类,然后派生类,同样是虚基类或者同样是普通基类的话根据继承顺序,不是按照初始化列表顺序。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 5月10日
  • 已采纳回答 5月10日
  • 创建了问题 5月10日

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用