Class

A class is a user-defined type.

https://en.cppreference.com/w/cpp/language/classes

Inheritance

The capability of a class to derive properties and characteristics from another class is called Inheritance. 一个类从另一个类派生属性和特性的能力称为继承

https://en.cppreference.com/w/cpp/language/derived_class

Overload 重载

functions can have the same name but different type of parameters and different number of parameters.

Operating overloading allows us to make operators work for user-defined classes

同一作用域中,同名函数的形式参数(指参数的个数、类型或者顺序)不同时,构成函数重载。

应用:操作符重载,为用户定义类型的操作数定制 C++ 运算符

Operator overloading is an example of C++ polymorphism.

https://en.cppreference.com/w/cpp/language/operators

Override 重写

指定一个虚函数覆盖另一个虚函数

一般用于子类继承父类时,重写(覆盖)一个方法,是对方法的实现过程进行重新编写。

在派生类中覆盖基类中的同名函数,要求基类函数必须是虚函数

https://en.cppreference.com/w/cpp/language/override

Virtual Function

Virtual functions are used with inheritance, they are called according to the type of object pointed or referred.

Following things are necessary to write a C++ program with runtime polymorphism (use of virtual functions)

  1. A base class and a derived class.
  2. A function with same name in base class and derived class.
  3. A pointer or reference of base class type pointing or referring to an object of derived class.
#include<iostream>
using namespace std;

class Base {
public:
    virtual void show() { cout<<" In Base \n"; }
};

class Derived: public Base {
public:
    void show() { cout<<"In Derived \n"; }
};

int main(void) {
    Base *bp = new Derived;
    bp->show(); // RUN-TIME POLYMORPHISM
    return 0;
}

output

In Derived

dynamic single-dispatch subtype polymorphism 动态(运行期生效) 单分派(基于一个类型去选择调用哪个函数) 子类型多态

纯虚函数:** 函数后面加 = 0,代表函数没有被实现

Template

函数模板针对仅参数类型不同的函数

template <typename AnyType>
void Swap(AnyType &a, AnyType &b)
{
    AnyType temp;
    temp = a;
    a = b;
    b = temp;
}
// funtemp.cpp -- using a function template
#include <iostream>
// function template prototype
template <typename T> // or class T
void Swap(T &a, T &b);
int main()
{
    using namespace std;
    int i = 10;
    int j = 20;
    cout << "i, j = " << i << ", " << j << ".\n";
    cout << "Using compiler-generated int swapper:\n";
    Swap(i, j); // generates void Swap(int &, int &)
    cout << "Now i, j = " << i << ", " << j << ".\n";
    double x = 24.5;
    double y = 81.7;
    cout << "x, y = " << x << ", " << y << ".\n";
    cout << "Using compiler-generated double swapper:\n";
    Swap(x, y); // generates void Swap(double &, double &)
    cout << "Now x, y = " << x << ", " << y << ".\n";
    // cin.get();
    return 0;
}
// function template definition
template <typename T> // or class T
void Swap(T &a, T &b)
{
    T temp; // temp a variable of type T
    temp = a;
    a = b;
    b = temp;
}

类模板针对仅数据成员成员函数类型不同的类

https://en.cppreference.com/w/cpp/language/templates

https://www.cnblogs.com/gw811/archive/2012/10/25/2738929.html

02-14 02:15