2024.03.18作业

封装一个动物的基类,类中有私有成员:姓名,颜色,指针成员年纪

再封装一个狗类,共有继承于动物类,自己拓展的私有成员有:指针成员腿的个数,共有成员函数:叫

要求:完成类中的构造函数,析构函数,拷贝构造函数,拷贝复制函数

#include <iostream>

using namespace std;

class Animal
{
private:
	string name;
	string color;
	int* age;

public:
	Animal() {}
	Animal(string name, string color, int age) :name(name), color(color), age(new int(age))
	{
		cout << "Animal类有参构造函数" << endl;
	}

	~Animal()
	{
		cout << "Animal类析构函数" << endl;
		delete age;
	}

	Animal(const Animal& other) :name(other.name), color(other.color), age(new int(*other.age))
	{
		cout << "Animal类拷贝构造函数" << endl;
	}

	Animal& operator=(const Animal& other)
	{
		cout << "Animal类拷贝赋值函数" << endl;
		if (this != &other)
		{
			name = other.name;
			color = other.name;
			age = new int(*other.age);
		}
		return *this;
	}
};

class Dog :public Animal
{
private:
	int* count;

public:
	Dog() {}
	Dog(string name, string color, int age, int count) :Animal(name, color, age), count(new int(count))
	{
		cout << "Dog类有参构造函数" << endl;
	}

	~Dog()
	{
		cout << "Dog类析构函数" << endl;
		delete count;
	}

	Dog(const Dog& other) :Animal(other), count(new int(*other.count))
	{
		cout << "Dog类拷贝构造函数" << endl;
	}

	Dog& operator=(const Dog& other)
	{
		cout << "Dogs类拷贝赋值函数" << endl;
		if (this != &other)
		{
			Animal::operator=(other);
			count = new int(*other.count);
		}
		return *this;
	}

	void speak()
	{
		cout << "汪汪汪" << endl;
	}
};

int main()
{
	Dog d1;
	Dog d2("11", "0x6633ff", 3, 4);
	Dog d3(d2);
	d1 = d3;

	return 0;
}

定义一个基类Animal,其中有一个虚函数perform(),用于在子类中实现不同的表演行为

#include <iostream>

using namespace std;

class Animal
{
protected:
	string name;
	int age;
	string hobby;

public:
	Animal() {}

	Animal(string name, int age, string hobby) :name(name), age(age), hobby(hobby) {}

	virtual void perform() = 0;
};

class Dog :public Animal
{
private:
	int* count;

public:
	Dog() {}

	Dog(string name, int age, string hobby) :Animal(name, age, hobby) {}

	void perform()
	{
		cout << "名称:" << this->name << endl;
		cout << "年龄:" << this->age << endl;
		cout << "爱好与表演:" << this->hobby << endl;
	}
};

int main()
{
	Dog d1("大黄", 3, "吃骨头");
	Animal *animal = &d1;

	animal->perform();

	return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值