一个c++的问题
一个c++的问题定义一个哺乳动物Mammal类,派生出狗Dog类,定义一个Dog类的对象,写出基类与派生类的构造函数与析构函数的调用顺序。(能否给我详细的解答,谢谢)#i...
一个c++的问题定义一个哺乳动物Mammal类,派生出狗Dog类,定义一个Dog类的对象,写出基类与派生类的构造函数与析构函数的调用顺序。(能否给我详细的解答,谢谢)
#include<iostream.h>
enum myColor{BLACK,WHITE};
class Mammal
{
public:
Mammal( );
~ Mammal( );
int GetAge( )const { return itsAge;}
void SetAge(int age) { itsAge=age;}
int GetWeight( )const { return itsWeight;}
void SetWeight(int weight ) { itsWeight=weight;}
void Speak( )const { cout<<”Mammal sound! \n”;}
protected:
int itsAge;
int itsWeight;
};
class Dog:public Mammal
{
public:
Dog( );
~Dog( );
myColor GeiColor( )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( ):itsColor()
{ cout<<”Dog destructor\n”; }
int main( )
{
Dog Jack;
Jack.Speak( );
Jack.WagTail( );
cout<<”Jack is”<<Jack.GetAge( )<<”year old\n”;
return 0;
} 展开
#include<iostream.h>
enum myColor{BLACK,WHITE};
class Mammal
{
public:
Mammal( );
~ Mammal( );
int GetAge( )const { return itsAge;}
void SetAge(int age) { itsAge=age;}
int GetWeight( )const { return itsWeight;}
void SetWeight(int weight ) { itsWeight=weight;}
void Speak( )const { cout<<”Mammal sound! \n”;}
protected:
int itsAge;
int itsWeight;
};
class Dog:public Mammal
{
public:
Dog( );
~Dog( );
myColor GeiColor( )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( ):itsColor()
{ cout<<”Dog destructor\n”; }
int main( )
{
Dog Jack;
Jack.Speak( );
Jack.WagTail( );
cout<<”Jack is”<<Jack.GetAge( )<<”year old\n”;
return 0;
} 展开
2个回答
展开全部
构造的时候 先构造基类 再构造派生类.
析构的时候 先析构派生类 再析构基类.
所以 这里顺序是
定义对象Dog Jack; 先调用 Mammal( )构造, 然后调用 Dog()构造.
程序结束时, 先调用~Dog析构, 再调用~Mammal析构.
构造和析构部分的打印为
Mammal constructor?
Dog constructor?
...
Dog destructor?
Mammal destructor?
PS你的~Dog写的有问题 应该是
Dog::~Dog( )
{ cout<<"Dog destructor?\n"; }
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询