前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【玩转腾讯云】C++学习笔记-模板

【玩转腾讯云】C++学习笔记-模板

原创
作者头像
买唯送忧
修改2021-05-04 14:22:27
1.7K0
修改2021-05-04 14:22:27
举报
文章被收录于专栏:虚拟技术学习虚拟技术学习

一、模板

1、类模板

类模板意思是先把类里面的数据类型待定,之后通过模板再来定义数据类型,详情看以下代码。

代码语言:javascript
复制
//类模板的写法
template <class T>
class Cml
{
public:
    Cml(T _age = 18, T _weight = 90): age(_age), weight(_weight){}
    T getAge() const {return age;}
    T getWeight() const {return weight;}
    //类模板中成员函数在类内的写法
    Cml& operator+=(const Cml& ss)
    {
        this->age += ss.age;
        this->weight += ss.weight;
        return *this;  
    }
private:
    T age, weight;
};

//成员函数在类外
template <class T>
Cml<T>& Cml<T>::operator+=(const Cml<T>& ss)
{
    this->age += ss.age;
    this->weight += ss.weight;
    return * this;
}

//main函数调用
    Cml<double> cml(80, 160);
    Cml<double> cml1(-70, -50);
    cml += cml1;
    std::cout << cml.getAge() << endl;
    //输出结果是10

2、函数模板

相比之下,函数模板就比类模板简单许多:如下

代码语言:javascript
复制
template <class T>
class Cml
{
public:
    Cml(T _age = 18, T _weight = 90): age(_age), weight(_weight){}
    T getAge() const {return age;}
    T getWeight() const {return weight;}
    Cml& operator+=(const Cml& ss);
    bool operator <(const Cml& ss) const {return age < ss.age;}//为下列的min函数服务
//    {
//        this->age += ss.age;
//        this->weight += ss.weight;
//        return *this;
//    }
private:
    T age, weight;
};

template <class T>
Cml<T>& Cml<T>::operator+=(const Cml<T>& ss)
{
    this->age += ss.age;
    this->weight += ss.weight;
    return * this;
}

//函数模板
template <class T>//这个T与上面的T表达的意思不一样,名字可以随便起
inline const T& min(const T& a, const T& b)
{
    return b < a ? b : a;
}

//先看main里的调用
    Cml<double> cml(80, 160);
    Cml<double> cml1(-70, -50);
    cml += cml1;
    std::cout << cml.getAge() << endl;
    //以上是类模板,传递的T是double需要在类名后面表明
    //而下面传递的是cml类型,,也就是Cml<double>类型,故而T是不一样的
    //函数模板需要指定类型,编译器会对其进行实参推导,推导出T为Cml<T>故而调用operator<
    Cml<double> a = min(cml, cml1);
    cout << a.getAge() << endl;
    //输出70

3、成员模板

成员模板即在类里面再写模板template,从而实现特殊的效果,比如:

代码语言:javascript
复制
template <class T>
class Cml1 : public Cml<T>
{
    template<class T1>
    explicit Cml1(T1 _age, T1 _weight):Cml<T>(_age, _weight){}
};

//在main函数里就可以实现这样一种写法,技术Base是父类,dep是子类
Cml1<Base> ss = new dep(..., ...);//模拟up_cast

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、模板
    • 1、类模板
      • 2、函数模板
        • 3、成员模板
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档