构造函数与析构函数举例

该博客展示了C++中构造函数和析构函数的使用。通过Mammal和Dog类的定义,解释了如何初始化成员变量,并在对象创建和销毁时调用相应的构造和析构函数。示例代码中,Dog类继承自Mammal类,并添加了特定的行为方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值