c++之抽象类的纯虚析构函数

一、抽象类

1、纯虚函数
形式:virtual 函数原型=0;
定义:在定义一个表达抽象概念的基类时,有时无法给出某些函数的具体实现方法,就可以将这些函数声明为纯虚函数。

2.抽象类
定义:声明了纯虚函数的类,都成为抽象类。
主要特点:抽象类只能作为基类来派生新类,不能声明抽象类的对象。(既然都是一个抽象概念了,纯虚函数没有具体实现方法,故不能创造该类的实际的对象)

但是可以声明指向抽象类的指针变量引用变量,通过指针或引用,就可以指向并访问派生类对象,进而访问派生类的成员。(体现了多态性)

作用:因为其特点,基类只是用来继承,可以作为一个接口,具体功能在派生类中实现(接口)

#include<iostream>
#include<map>
using namespace std;

class shape
{
protected:
	int x;
	int y;
public:
	void set(int i, int j)
	{
		x = i;
		y = j;
	}
	//纯虚函数实现抽象类
	virtual void area() = 0;
};

class Rectangle :public shape
{
	void area()
	{
		cout << x * y << endl;
	}
};

class Triangle :public shape
{
	void area()
	{
		cout << x * y*0.5 << endl;
	}
};

int main()
{
	Rectangle R;
	Triangle T;
	//抽象类不能创建对象,但是可以使用指针或者引用访问继承类成员
	shape *s;

	s = &R;
	s->set(2,3);
	s->area();

	s = &T;
	s->set(2,3);
	s->area();

	system("pause");
	return 0;
}
/*
6
3
*/

二、虚析构函数
之前我们写过c++之不能声明为虚函数的函数包括普通函数、构造函数、内联成员函数、静态成员函数、友元函数。这里没有析构函数,说明析构函数可以是虚函数。

#include<iostream>
#include<map>
using namespace std;

class Base
{
public:
	Base() { cout << "Base:构造" << endl; }
	virtual ~Base() { cout << "Base:析构" << endl; }
};

class Derived : public Base
{
public:
	Derived() { cout << "Derived:构造" << endl; };
	~Derived() { cout << "Derived:析构" << endl; };
};

int main()
{
	Base *pb;
	pb = new Derived;
	delete pb;

	system("pause");
	return 0;
}

在这里插入图片描述

注意构造函数与析构函数的执行顺序

三、纯虚析构函数

定义纯虚函数的真正目的是为了定义抽象类,而并不是函数本身

所以我们把上面的代码修改为:

class Base  
{  
    public:  
        Base(){cout << "Base:构造" << endl;}  
        virtual ~Base()= 0;  
}; 

但是会报link错误,不能找到~Base()的引用:

error LNK2019: 无法解析的外部符号 “public: virtual __thiscall Base::~Base(void)” (??1Base@@UAE@XZ),该符号在函数
__unwindfunclet$??0Derived@@QAE@XZ$0 中被引用

报错原因:
析构函数、构造函数和其他内部函数不一样,在调用时,编译器需要产生一个调用链,调用顺序如上述例子所示。也就是,Derived的析构函数里面隐含调用了Base的析构函数。而刚才的代码中,缺少~Base()的函数体,当然会出现错误。

我们完全可以为纯虚函数指定函数体 。通常的纯虚函数不需要函数体,是因为我们一般不会调用抽象类的这个函数,只会调用派生类的对应函数。这样,我们就有了一个纯虚析构函数的函数体,上面的代码需要改成:

#include<iostream>
#include<map>
using namespace std;

class Base
{
public:
	Base() { cout << "Base:构造" << endl; }
	virtual ~Base() = 0;
};
Base::~Base()
{
	cout << "Base:析构" << endl;
}

class Derived : public Base
{
public:
	Derived() { cout << "Derived:构造" << endl; };
	~Derived() { cout << "Derived:析构" << endl; };
};

int main()
{
	Base *pb;
	pb = new Derived;
	delete pb;

	system("pause");
	return 0;
}

在这里插入图片描述

  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值