1.3.2 类模板和函数模板的区别

125 阅读1分钟

区别:

  1. 类模板没有自动类型推导的使用方式
  2. 类模板在参数列表中允许默认参数
#include <iostream>
#include <string>

using namespace std;

template<class NameType, class AgeType=int>
class Person
{
public:
	Person(NameType name, AgeType age)
	{
		this->name = name;
		this->age = age;
	}
	void show_info()
	{
		cout << "Name: " << name << endl;
		cout << "Age: " << age << endl;
	}
	NameType name;
	AgeType age;
};

void test()
{
	// 如果没有默认类型,必须指定数据类型
	Person<string, int> p1("Li", 20);
	p1.show_info();
	Person<string> p2("Li", 26);
	p2.show_info();
}

int main()
{
	test();

	system("pause");
	return 0;
}