【SEU程序设计课笔记】 25 - 2021/01/07 - Write C++ programs - 类的继承/类的聚合

类的继承(inheritance)

OPP 抽象:找到不同东西的共同特点)
往上抽象的:基类(父类) - base class
向下具体的:派生类(子类) - derived class

虚函数

C++ Primer (5th Edition, English Version) Page 592

The base class defines as virtual those functions it expects its derived classes to define for themselves.

C++ Primer (5th Edition, English Version) Page 595

The virtual keyword appears only on the declaration inside the class and may not be used on a function definition that appears outside the class body.

纯虚函数(pure virtual function)

多态

静态:重载(overload)
动态:覆盖(override)
C++ Primer (5th Edition, English Version) Page 593

Because the derived class uses public in its derivation list, we can use objects of type of the base type as if they were the derived class objects.

保护(protected)

C++ Primer (5th Edition, English Version) Page 595

However, sometimes a base class has members that it wants to let its derived classes use while still prohibiting access to those same members by other users. We specify such members after a protected access specifier.

类的聚合

对象与对象的包含。

class Car
{
private:
	Engine eng; // Engine is also a class.
}

强聚合:同生共死。弱聚合,成员可换。

Example

积分器:

#include <iostream>
#include <iomanip> // setprecision
using namespace std;

constexpr double PI = 3.1415926535897932384625;

// base class
class Integrator
{
public:
	virtual double fun(double x) const = 0;
	
	double Integrate(const double x1, const double x2)
	{
		double step = 1E-8;

		double sum = 0;
		for (double x = x1; x < x2; x += step)
		{
			double x_ = x + step;
			if (x_ > x2) x_ = x2;
			double y1 = fun(x);
			double y2 = fun(x_);
			sum += (y1 + y2) * (x_ - x) / 2;
		}
		return sum;
	}
};

// derived class
class Integrator_sin : public Integrator
{
	double fun(double x) const
	{
		return sin(x);
	}
};

// derived class
class Integrator_x2 : public Integrator
{
	double fun(double x) const
	{
		return x * x;
	}
};

int main(int argc, char** argv)
{
	Integrator_sin i1;
	Integrator_x2  i2;

	cout << "1: sin(x) " << setprecision(10) << i1.Integrate(0, PI / 2) << endl;
	cout << "2: x^2    " << setprecision(10) << i2.Integrate(0, 1) << endl;

	return 0;
}

Output:
Output


ALL RIGHTS RESERVED © 2021 Teddy van Jerry
欢迎转载,转载请注明出处。


See also

Teddy van Jerry 的导航页

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值