一.定义一个哺乳动物Mammal类,再由此派生出狗Dog类,定义一个Dog类的对象,观察基类与派生类的构造函数与析构函数的调用顺序。
1.我们按照题目要求写出对应代码,然后观察输出结果来确定调用顺序就好了。
2.
3.伪代码:
类 mammal{ public: 构造函数(){输出} private: age weight; }; 类 dog: public mammal{ public: 构造函数(){输出} private: name color }; main(){ dog a; return 0; }
代码:
#include<iostream> using namespace std; class Mammal { protected: int age, weight; public: Mammal() :age(1), weight(5) { cout << "Mammal constructor..." << endl; } ~Mammal() { cout << "Mammal destructor..." << endl; } const int getage() { return age; } void setage(int a) { age = a; } const int getweight() { return weight; } void steweight(int a) { weight = a; } }; class dog :public Mammal{ private: string color; string name; public: dog():color("white"), name("xiaobai") { cout << "dog constructor..." << endl; } ~dog(){ cout << "dog destructor..." << endl; } string getcolor() { return color; } void setcolor(string s) { color = s; } string getname() { return name; } void setname(string s) { name = s; } }; int main() { dog xiaobai; cout << "xiaobai is " << xiaobai.getage() << " years old" << endl; return 0; }
4.总结:先调用基类的构造函数再调用派生类对象的构造函数
标签:调用,weight,每日,age,Mammal,打卡,public,构造函数 From: https://www.cnblogs.com/leapssisbird/p/17304376.html