C++学习笔记--抽象类-纯虚函数

什么是抽象类?面向对象中的抽象类可用于表示现实世界中的抽象概念,是一种只能定义类型,而不能产生对象的类,它只能被继承并重写相关函数,在抽象类中的相关函数最直接的表现特征就是没有完整的实现。比如现实世界中的图形,它是一个抽象的概念,但是又无法缺少,如果将图形做成一个类的话那么图形就可以说成是一个抽象类,如果我们说要对图形求面积的话是行不通的,因为没有指定具体的图形类型,没有任何意义,但是现实中缺少了这个概念又显然是不行的,因此,在程序设计中必须能够反映抽象的图形,我们通过抽象类表示,抽象类不能创建对象,只能用于继承,就好比拿出一个具体形状的图形让你求面积这样就是可行的。

但是C++中并没有抽象类的概念,只能通过纯虚函数实现抽象类,纯虚函数是指只定义原型的成员函数,在一个类中,只要存在纯虚函数那么这个类就是抽象类。如何实现纯虚函数呢?

class Shape
{
public:
	virtual double Circumference() = 0;
	virtual double Area() = 0;
	virtual void display() = 0;
};
形如上面就实现了一个抽象类,在 虚函数声明后面加上"=0"表示告诉编译器当前是声明纯虚函数,因此不再需要定义函数体

抽象类不能定义对象,但是可以定义指针,可以通过指针调用纯虚函数,它指向的肯定是抽象类的子类的同名函数,这在实现多态中讲解过。

几点注意:

抽象类只能用作父类并被继承。

子类中必须实现纯虚函数的具体功能。

纯虚函数被实现后成为虚函数。

如果子类没有实现纯虚函数,则子类变成抽象类。

什么叫做接口?满足以下条件的就被称作接口:

类中没有定义任何的成员变量。

所有的成员函数都是公有的。

所有的成员函数都是纯虚函数,所以它是一种特殊的抽象类。

实现一个使用抽象类的例子,定义一个图形的抽象类,包含求面积、求周长和显示函数,在子类中实现具体图形的设计。最后求两个图形的面积和、周长和。

#include <iostream>
#include <math.h>
using namespace std;
#define PI 3.1415

//抽象类
class Shape
{
public:
	virtual double Circumference() = 0;
	virtual double Area() = 0;
	virtual void display() = 0;
};

class Circle : public Shape
{
	double r;
public:
	Circle()
	{
		r = 0;
	}
	Circle(double r)
	{
		this->r = r;
		cout << "Circle(double r)" << endl;
	}
	double Circumference()
	{
		return 2*PI*r;
	}
	double Area()
	{
		return PI*r*r;
	}
	void display()
	{
		cout << "r = " << r << endl;
		cout << "Circumference = " << Circumference() << endl;
		cout << "Area = " << Area() << endl;
	}
};

class Rectangle : public Shape
{
	double length,wide;
public:
	Rectangle()
	{
		length = 0;
		wide = 0;
	}
	Rectangle(double length,double wide)
	{
		this->length = length;
		this->wide = wide;
		cout << "Rectangle(double length,double wide)" << endl;
	}
	double Circumference()
	{
		return 2 * (length + wide);
	}
	double Area()
	{
		return length*wide;
	}
	void display()
	{
		cout << "length = " << length << '\t' << "wide = " << wide << endl;
		cout << "Circumference = " << Circumference() << endl;
		cout << "Area = " << Area() << endl;
	}


};

void area_sum(Shape **p)
{
    double sum = 0.0;
    for(int i = 0; i < 2; i++)
        sum += p[i]->Area();

        cout << "area = " << sum << endl;
}


void length_sum(Shape **p)
{
    double sum = 0.0;
    for(int i = 0; i < 2; i++)
        sum += p[i]->Circumference();

        cout << "Circumference = " << sum << endl;
}

int main()
{
	Shape *shape[2];

	Circle circle(10);
	Rectangle rectangle(1,2);
	cout << endl << endl;

	shape[0] = &circle;
	shape[0]->display();
	cout << endl;

	shape[1] = &rectangle;
	shape[1]->display();
	cout << endl;

    area_sum(shape);
    length_sum(shape);


	cout << "hello" << endl;
	return 0;
}
输出结果为:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值