编程语言
首页 > 编程语言> > 【C++】多态&数据抽象&抽象类

【C++】多态&数据抽象&抽象类

作者:互联网

目录

来源

C++多态

概念理解来源于 菜鸟论坛.
运行原理来源于 CSDN.

#include "stdafx.h"
#include <iostream> 
using namespace std;

class Shape {
protected:
	int width, height;
public:
	Shape(int a = 0, int b = 0)
	{
		width = a;
		height = b;
	}
	virtual int area() 
	{
		cout << "Rectangle class area :" << width + height << endl;
		//return (width * height);
		return (0);
	}
};
class Rectangle : public Shape {
public:
	Rectangle(int a = 0, int b = 0) :Shape(a, b) { }
	int area()
	{
		cout << "Rectangle class area :" << width * height << endl;
		//return (width * height);
		return (0);
	}
};
class Triangle : public Shape {
public:
	Triangle(int a = 0, int b = 0) :Shape(a, b) { }
	int area()
	{
		cout << "Triangle class area :" << width * height / 2 << endl;
		//return (width * height / 2);
		return(0);
	}
};
// 程序的主函数
int main()
{
	Shape *shape;
	Rectangle rec(10, 7);
	Triangle  tri(10, 7);
	Shape base(10, 7);

	shape = &base;
	shape->area();

	// 存储矩形的地址
	shape = &rec;
	// 调用矩形的求面积函数 area
	shape->area();

	// 存储三角形的地址
	shape = &tri;
	// 调用三角形的求面积函数 area
	shape->area();

	while (1);

	return 0;
}

若将基类中的虚函数写为纯虚函数

virtual int area() = 0;

则在编译时会有
在这里插入图片描述
这里出现了抽象类的概念。

C++数据抽象

要了解抽象类我们首先学习抽象数据。
概念理解来源于 菜鸟论坛.

#include "stdafx.h"
#include <iostream>
using namespace std;

class Adder {
public:
	// 构造函数
	Adder(int i = 0)
	{
		total = i;
	}
	// 对外的接口
	void addNum(int number)
	{
		total += number;
	}
	// 对外的接口
	int getTotal()
	{
		return total;
	};
private:
	// 对外隐藏的数据
	int total;
};
int main()
{
	Adder a(2);

	a.addNum(10);
	a.addNum(20);
	a.addNum(30);

	cout << "Total " << a.getTotal() << endl;
	while (1);
	return 0;
}

运行结果 Total 62
符合预期。

抽象类(接口)

概念理解来源于 菜鸟论坛.

#include "stdafx.h"
#include <iostream>
using namespace std;

// 基类
class Shape
{
public:
	// 提供接口框架的纯虚函数
	virtual int getArea() = 0;
	void setWidth(int w)
	{
		width = w;
	}
	void setHeight(int h)
	{
		height = h;
	}
protected:
	int width;
	int height;
};

// 派生类
class Rectangle : public Shape
{
public:
	int getArea()
	{
		return (width * height);
	}
};
class Triangle : public Shape
{
public:
	int getArea()
	{
		return (width * height) / 2;
	}
};

int main(void)
{
	Rectangle Rect;
	Triangle  Tri;

	Rect.setWidth(5);
	Rect.setHeight(7);
	// 输出对象的面积
	cout << "Total Rectangle area: " << Rect.getArea() << endl;

	Tri.setWidth(5);
	Tri.setHeight(7);
	// 输出对象的面积
	cout << "Total Triangle area: " << Tri.getArea() << endl;
	while (1);
	return 0;
}

这个例子简单易懂,不需要过多赘述。

标签:area,int,多态,height,数据抽象,width,抽象类,include,public
来源: https://www.cnblogs.com/vrijheid/p/14223048.html