类的继承(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:
ALL RIGHTS RESERVED © 2021 Teddy van Jerry
欢迎转载,转载请注明出处。