纯虚函数之析构函数

纯虚函数可以有函数体(可以有但最好不要加)。当基类析构函数为纯虚函数时,必须显示加上函数体。
#include <iostream>
using namespace std;

class Base
{
public:
	virtual void print() =0;

	virtual void print1() = 0
	{
		cout<< "Base print1" <<endl;
	}

	virtual ~Base() = 0
	{
		cout<< "~Base" <<endl;
	}
};



class Deriver:public Base
{
public:
	void print()
	{
		cout<< "Deriver print" <<endl;
	}

	void print1()
	{
		cout<< "Deriver print1" <<endl;
	}

	~Deriver()
	{
		cout<< "~Deriver" <<endl;
	}
};

void main()
{
	Deriver d;
	
	d.print();
	//d.Base::print();//error

	d.print1();
	d.Base::print1();
}

当一个类中有至少一个纯虚函数,我们称之为抽象类。抽象类不能被实例化,只能被继承。在抽象类中定义的纯虚函数不需要实现。但是,如果抽象类中有成员变量需要在析构函数中被释放,那么该类的析构函数必须被定义。 下面是一个例子,展示如何在抽象类中定义纯虚函数析构函数的实现: ```c++ #include <iostream> class Shape { public: virtual ~Shape() = 0; // 纯虚析构函数 virtual void draw() = 0; // 纯虚函数 void setX(int x) { this->x = x; } void setY(int y) { this->y = y; } int getX() const { return x; } int getY() const { return y; } protected: int x; int y; }; Shape::~Shape() { std::cout << "Shape destructor called." << std::endl; } class Circle : public Shape { public: void draw() override { std::cout << "Drawing a circle at (" << getX() << ", " << getY() << ")" << std::endl; } }; class Rectangle : public Shape { public: void draw() override { std::cout << "Drawing a rectangle at (" << getX() << ", " << getY() << ")" << std::endl; } }; int main() { Shape* shapes[2] = {new Circle(), new Rectangle()}; shapes[0]->setX(10); shapes[0]->setY(20); shapes[1]->setX(30); shapes[1]->setY(40); for(int i = 0; i < 2; i++) { shapes[i]->draw(); delete shapes[i]; } return 0; } ``` 在这个例子中,我们定义了一个抽象类 `Shape`,其中包含一个纯虚函数 `draw()` 和一个成员变量。由于 `Shape` 是一个抽象类,因此其析构函数必须是一个纯虚析构函数。在 `Shape` 的析构函数中,我们打印一条消息,以便在对象被销毁时进行调试。 我们还定义了两个继承自 `Shape` 的类:`Circle` 和 `Rectangle`。这两个类都实现了 `draw()` 函数。 在 `main()` 函数中,我们创建了一个 `Shape` 指针类型的数组,并使用 `new` 运算符在堆上创建了两个对象:`Circle` 和 `Rectangle`。我们设置了每个对象的 `x` 和 `y` 坐标,并调用了它们的 `draw()` 函数。最后,我们使用 `delete` 运算符释放了数组中的每个对象。 该程序的输出应该如下所示: ``` Drawing a circle at (10, 20) Shape destructor called. Drawing a rectangle at (30, 40) Shape destructor called. ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值