xiximayou

1.类模板没有自动类型推导;

2.类模板在模板参数列表中可以有默认参数;

#include<iostream>
using namespace std;

template<class NameType,class AgeType=int>
class Person {
public:
    NameType name;
    AgeType age;
    Person(NameType name, AgeType age) {
        this->name = name;
        this->age = age;
    }
};

void test() {
    //Person<> p("tom",22);无法自动类型推导,只能显示指明类型
    Person<string,int> p("tom",22);
    cout << p.name << " " <<p.age << endl;
    //可以先在参数中声明类型,这里就可以不指明了
    Person<string> p2("jack", 23);
    cout << p2.name << " " << p2.age << endl;
}

int main() {
    test();
    system("pause");
    return 0;
}

分类:

技术点:

相关文章: