定义一个哺乳动物 Mammal 类,再由此派生出狗 Dog 类,定义一个 Dog 类的对象,观察 基类与派生类的构造函数与析构函数的调用顺序。
解:
源程序:
#include <iostream.h> enum myColor{ BLACK, WHITE }; class Mammal { public: // constructors Mammal(); ~Mammal(); //accessors int GetAge() const { return itsAge; } void SetAge(int age) { itsAge = age; } int GetWeight() const { return itsWeight; } void SetWeight(int weight) { itsWeight = weight; } //Other methods void Speak() const { cout << "Mammal sound!\n"; } protected: int itsAge; int itsWeight; }; class Dog : public Mammal { public: Dog(); ~Dog(); myColor GetColor() const { return itsColor; } void SetColor (myColor color) { itsColor = color; } void WagTail() { cout << "Tail wagging...\n"; } private: myColor itsColor; }; Mammal::Mammal(): itsAge(1), itsWeight(5) { cout << "Mammal constructor...\n"; } Mammal::~Mammal() { cout << "Mammal destructor...\n"; } Dog::Dog(): itsColor (WHITE) { cout << "Dog constructor...\n"; } Dog::~Dog() { cout << "Dog destructor...\n"; } int main() { Dog Jack; Jack.Speak(); Jack.WagTail(); cout << " Jack is " << Jack.GetAge() << " years old\n"; return 0; }
程序运行输出:
Mammal constructor...
Dog constructor...
Mammal sound!
Tail wagging...
Fido is 1 years old
Dog destructor...
Mammal destructor...
这道题你会答吗?花几分钟告诉大家答案吧!
扫描二维码,关注牛客网
下载牛客APP,随时随地刷题
解:
源程序:
程序运行输出:
Mammal constructor...
Dog constructor...
Mammal sound!
Tail wagging...
Fido is 1 years old
Dog destructor...
Mammal destructor...