纯虚函数和抽象类(C++)

4.2 纯虚函数和抽象类

4.2.1 纯虚函数

如果一个虚函数仅表达抽象的行为,没有具体的功能,即只有声明没有定义,这样的虚函数被称为纯虚函数抽象方法

class 类名 {
public:
    virtual 返回类型 函数名 (形参表)= 0};

假设有图形类Figure,设计计算面积的成员函数area()。Figure只是一个纯抽象意义上的概念,不存在计算面积或体积的具体方法,所以只能将成员函数area()设计为纯虚函数。

#include <iostream>
using namespace std;
class Figure{
protected:
    double x, y;
public:
    void set(double i, double j){
        x = i;
        y = j;
    }
    virtual void area()=0;
};

4.2.2 抽象类

如果类中包含了纯虚函数,那么这个类就是抽象类,抽象类只能最为其他类的基类,不能用来建立对象。

如果类中的所有成员函数都是纯虚函数则可以称为纯抽象类

#include <iostream>
using namespace std;

class Shape{ //形状  抽象类
public:
	virtual void draw() = 0; //纯虚函数
};

class Rect : public Shape{ //矩形
public:
	void draw(){
		cout << "Rect draw" << endl;
	}
};

class Circle : public Shape{ //圆形
public:
	void draw(){
		cout << "Circle draw" << endl;
	}
};

class Ellipse : public Shape{ //椭圆
public:
	void draw(){
		cout << "Ellipse draw" << endl;
	}
};

int main(void) {
	
//	Shape s1; //error 抽象类不能用来建立对象
	Shape *ps[128] = {0};

	ps[0] = new Rect;
	ps[1] = new Circle;
	ps[2] = new Ellipse;

	for(int i = 0; ps[i] != NULL; i++){
		ps[i]->draw();
	}
	return 0;
}
  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值