14.2.2重学C++之【类模板和模板函数的区别】

#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;


/*
    1.3.2类模板和模板函数的区别
        1. 类模板没有自动类型推导的使用方式
        2. 类模板在模板参数列表中可以有默认参数(函数模板不可以有默认)
*/


template<class NameType, class AgeType>
class Person{
public:
    NameType name;
    AgeType age;

    Person(NameType _name, AgeType _age){
        this->name = _name;
        this->age = _age;
    }

    void show_info(){
        cout << "name:" << this->name << " age:" << this->age << endl;
    }
};


void test(){
    //Person p("tom", 30); // 报错   类模板无法进行"自动类型推导"
    Person <string, int> p("tom", 30); // ok   类模板只能用"显示指定类型"方式调用
    p.show_info();
}


template<class NameType, class AgeType = int> // 可以给出默认参数,即默认数据类型
class Person2{
public:
    NameType name;
    AgeType age;

    Person2(NameType _name, AgeType _age){
        this->name = _name;
        this->age = _age;
    }

    void show_info(){
        cout << "name:" << this->name << " age:" << this->age << endl;
    }
};


void test2(){
    Person2 <string> p2("amay", 18); // 有了默认类型后,可以省略不写
    p2.show_info();
}


int main(){
    test();
    test2();

    system("pause");
    return 0;
}

posted @ 2021-04-17 21:18  yub4by  阅读(85)  评论(0)    收藏  举报