1 /* 2 3 4 实验启示1:构造子类对象时,先调用父类构造函数,后调用子类构造函数 5 实验启示2:析构子类对象时,先调用子类析构函数,后调用父类析构函数 6 实验启示3:在这个对象生命周期结束时,析构函数会自动调用 7 8 9 */ 10 11 #include<iostream> 12 13 int flag; 14 15 class Animal 16 { 17 18 public: 19 20 int weight; 21 int length; 22 double hungry_rate; 23 24 Animal(void); 25 ~Animal(){flag++;std::cout<<flag<<". I‘m ~Animal(),now."<<std::endl;} 26 27 void eat(void); 28 29 }; 30 31 Animal::Animal() 32 { 33 flag++; 34 35 std::cout<<flag<<". I‘m Animal,now."<<std::endl; 36 37 weight=25; 38 Animal::length=10; 39 Animal::hungry_rate=70; 40 41 } 42 43 void Animal::eat(void) 44 { 45 46 std::cout<<"The Animal is eating"<<std::endl; 47 48 } 49 50 class Fish:public Animal 51 { 52 53 public: 54 55 Fish(){ flag++;std::cout<<flag<<". I‘m Fish,now."<<std::endl;} 56 ~Fish(){flag++;std::cout<<flag<<". I‘m ~Fish(),now."<<std::endl;} 57 58 void swim() 59 { 60 61 std::cout<<"The Fish Is Swimming!"<<std::endl; 62 63 } 64 }; 65 66 int main() 67 { 68 69 Fish x; 70 71 x.eat(); 72 73 std::cout<<x.hungry_rate; 74 75 x.swim(); 76 77 return 0; 78 }
运行结果:
时间: 2024-11-07 20:52:19