C++基础知识(4):泛型与模板

        模板是一种对类型进行参数化的工具,模板是泛型编程的基础,而泛型编程指的就是编写与类型无关的代码,是C++中一种常见的代码复用方式。模板分为模板函数和模板类;模板函数针对参数类型不同的函数;模板类主要针对数据成员和成员函数类型不同的类。

1.函数模板
template<class T>或template<typename T>
函数类型 函数名(参数列表)
{
    函数体;
}
template<class T1,class T2,...>//class可以换成typename
函数类型 函数名(参数列表)
{
    函数体;
}
//举个栗子
template<class T> T max(T a, T b)
{
    return a > b ? a : b;
}
int main()
{
    cout <<"max value is "<< max(12,34) << endl;//34
    cout << "max value is " << max(12.4, 13.6) << endl;//13.6
    cout << "max value is " << max(12.4, 13) << endl;//error 没有与参数列表匹配的 函数模板 "max" 实例参数类型为:(double, int)
    return 0;
}
2.类模板

声明了类模板,就可以将类型参数用于类的成员函数和成员变量了。换句话说,原来使用 int、float、char 等内置类型的地方,都可以用类型参数来代替。类模板的一般形式:

template<class T>//class可以换成typename 模板头
class 类名
{
    函数定义;
};
//多个类型参数和函数模板类似,逗号隔开

当类中的成员函数在类的声明之外定义时,它必须定义为函数模板,带上模板头,定义形式如下:

template<class T>//class可以换成typename
函数类型 类名<T>::函数名(形参列表)
{
    函数体;
}

举个例子:

template<typename T1, typename T2>  // 模板头  没有分号
class Point {
public:
    Point(T1 x, T2 y) : x(x), y(y) { }
public:
    T1 getX() const;  //成员函数后加const,声明该函数内部不会改变成员变量的值
    void setX(T1 x);  
    T2 getY() const;  
    void setY(T2 y);  
private:
    T1 x;  
    T2 y;  
};
template<typename T1, typename T2>  //模板头
T1 Point<T1, T2>::getX() const  {
    return x;
}
template<typename T1, typename T2>
void Point<T1, T2>::setX(T1 x) {
    x = x;
}
template<typename T1, typename T2>
T2 Point<T1, T2>::getY() const {
    return y;
}
template<typename T1, typename T2>
void Point<T1, T2>::setY(T2 y) {
    y = y;
}
int main()
{
    Point<int, double> p1(66, 20.5);
    Point<int, char*> p2(10, "东经33度");
    Point<char*, char*> *p3 = new Point<char*, char*>("西经12度", "北纬66度");
    cout << "x=" << p1.getX() << ", y=" << p1.getY() << endl;
    cout << "x=" << p2.getX() << ", y=" << p2.getY() << endl;
    cout << "x=" << p3->getX() << ", y=" << p3->getY() << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_55238862/article/details/135324511
今日推荐