知识点1:static静态变量在类内声明,但必须在类外初始化
知识点2:构造函数不能是虚函数
知识点3:如果基类构造函数里所有参数有缺省值,那么派生类函数可以不为其初始化,基类会自行用缺省值初始化变量
知识点4:一个派生类对象消亡时,除了会调用该派生类的析构函数,还会调用基类的析构函数(先派生后基类)
i.
1 #include <iostream> 2 using namespace std; 3 class Animal{ 4 public: 5 static int number; 6 Animal(int num = 1){Animal::number = Animal::number + num;} 7 virtual ~Animal(){-- Animal::number;} 8 }; 9 int Animal::number = 0; 10 11 class Dog:public Animal{ 12 public: 13 static int number; 14 Dog(int num = 1){ 15 Dog::number = Dog::number + num; 16 } 17 ~Dog(){-- Dog::number;} 18 }; 19 int Dog::number = 0; 20 21 class Cat:public Animal{ 22 public: 23 static int number; 24 Cat(int num = 1){ 25 Cat::number = Cat::number + num; 26 } 27 ~Cat(){-- Cat::number;} 28 }; 29 int Cat::number = 0; 30 void print() { 31 cout << Animal::number << " animals in the zoo, " << Dog::number << " of them are dogs, " << Cat::number << " of them are cats" << endl; 32 } 33 34 int main() { 35 print(); 36 Dog d1, d2; 37 Cat c1; 38 print(); 39 Dog* d3 = new Dog(); 40 Animal* c2 = new Cat; 41 Cat* c3 = new Cat; 42 print(); 43 delete c3; 44 delete c2; 45 delete d3; 46 print(); 47 }
ii.
1 #include <iostream> 2 using namespace std; 3 class Animal{ 4 public: 5 static int number; 6 Animal(/*int num = 1*/){} 7 virtual ~Animal(){-- Animal::number;} 8 }; 9 int Animal::number = 0; 10 11 class Dog:public Animal{ 12 public: 13 static int number; 14 Dog(int num = 1){ 15 Animal::number = Animal::number + num; 16 Dog::number = Dog::number + num; 17 } 18 ~Dog(){-- Dog::number;} 19 }; 20 int Dog::number = 0; 21 22 class Cat:public Animal{ 23 public: 24 static int number; 25 Cat(int num = 1){ 26 Animal::number = Animal::number + num; 27 Cat::number = Cat::number + num; 28 } 29 ~Cat(){-- Cat::number;} 30 }; 31 int Cat::number = 0; 32 void print() { 33 cout << Animal::number << " animals in the zoo, " << Dog::number << " of them are dogs, " << Cat::number << " of them are cats" << endl; 34 } 35 36 int main() { 37 print(); 38 Dog d1, d2; 39 Cat c1; 40 print(); 41 Dog* d3 = new Dog(); 42 Animal* c2 = new Cat; 43 Cat* c3 = new Cat; 44 print(); 45 delete c3; 46 delete c2; 47 delete d3; 48 print(); 49 }
2个代码体现了知识点3
标签:num,int,编程,number,Dog,026,Animal,填空,Cat From: https://www.cnblogs.com/balabalabubalabala/p/16647496.html