C++基础笔记---模版

104 阅读1分钟

模版

模版函数

使用模版函数不需要指定类型,直接传参就可以了。

template <typename T>
T& add(T& a, T& b) {
    return a+b;
}

add(1, 2);

模版类

使用模版类需要指定类型。

template <typename T>
class complex {
private:
    T r, i;

public:
    ...

    T& real() {
        return this->r;
    }
};

complex<int> c1(1, 2);

cout << c1.real();