C++问题,请问那个WHITE 有什么用,为什么要建立一个枚举类型 50
7-6定义一个哺乳动物Mammal类,再由此派生出狗Dog类,定义一个Dog类的对象,观察基类与派生类的构造函数与析构函数的调用顺序。解:源程序:#include<ios...
7-6 定义一个哺乳动物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 << "Tailwagging...\n"; }
private:
myColor itsColor;
};
Mammal::Mammal():
itsAge(1),
itsWeight(5)
{
cout << "Mammalconstructor...\n";
}
Mammal::~Mammal()
{
cout << "Mammaldestructor...\n";
}
Dog::Dog(): itsColor (WHITE)
{
cout << "Dogconstructor...\n";
}
Dog::~Dog()
{
cout << "Dogdestructor...\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... 展开
解:
源程序:
#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 << "Tailwagging...\n"; }
private:
myColor itsColor;
};
Mammal::Mammal():
itsAge(1),
itsWeight(5)
{
cout << "Mammalconstructor...\n";
}
Mammal::~Mammal()
{
cout << "Mammaldestructor...\n";
}
Dog::Dog(): itsColor (WHITE)
{
cout << "Dogconstructor...\n";
}
Dog::~Dog()
{
cout << "Dogdestructor...\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... 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询