c++ template学习笔记

template<class T>
xxxx function(){
}

===>>>

template<class T> xxxx function(){
}
template <class T>
class A
{
}
//指定派生类的类模板:int
class B : pubilc class<int> A
{
}
//指定派生类的类模板:template T
template<class T>
class B : pubilc class<T> A
{
}
类函数模板是怎么实现的? 二次编译,类中的模板成员函数,在调用的过程中,才生成对应的函数。如果是int类型的成员函数,就生成int类型的。 类模板内的函数在类外实现的。主要问题,产生在的friend函数。

#include <iostream>

using namespace std;


// 模板的类外声明:
template <class T> class Person;
template <class T> void print_t(Person<T> &s);




template<class T>
class Person
{
private:
    /* data */
    T mh;
    T mw;

public:
    Person(T h,T w):mh(h),mw(w){};

	// <T> : 是之前的类外声明的T,Person中的<T> 是 template<class T>
    friend void print_t<T>(Person<T> &s);

    void show();

    ~Person(){};
};


template<class T>
void Person<T>::show(){
    cout << this->mh << ","<< this->mw <<endl;
}

template<class T> // 此时的T,映射的Person中的T
void print_t(Person<T> &s){
    cout << s.mh << " ss," << s.mw << endl;
}




int main(){

    Person<int> s(90,88);
    s.show();
    print_t(s);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值