构造函数与析构函数举例

#include <iostream>

using namespace std;

enum BREED {GOLDEN,CAIRN,BUAG};

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的声音!\n";}
	void Sleep() const { cout << "I'm Sleeping.\n";}
protected:
	int itsAge;
	int itsWeight;
};

class Dog : public Mammal
{
public:
	Dog();
	~Dog();

	BREED GetBreed() const { return itsBreed;}
	void SetBreed(BREED breed) { itsBreed = breed;}

	void WagTail() const { cout << "Tail wagging... \n"; }
	void BegForFood() const { cout << "Begging for food ..\n"; }

private:
	BREED itsBreed;
};

Mammal::Mammal() : itsAge(2), itsWeight(5)
{
	cout << "Mammal的构造函数被调用。" << endl;
}

Mammal::~Mammal()
{
	cout << "~Mammal析构函数被调用。" << endl;
}

Dog::Dog() : itsBreed(GOLDEN)
{
	cout << "Dog的构造函数被调用。" << endl;
}

Dog::~Dog()
{
	cout << "~Dog的析构函数被调用。" << endl;
}

int main()
{
	Dog a;
	a.Speak();
	a.WagTail();
	cout << "a is " << a.GetAge() << " years ago." << endl; 


	return 0;
}

你可能感兴趣的:(构造函数与析构函数举例)