模板——类模板1--与函数的关系

1.类模板基本语法

template<class T,class T2>

template<class NameType,class AgeType>
class Person
{
public:
	Person(NameType name,AgeType age)
	{
		this->m_name = name;
		this->m_age = age;
	}
	void ShowPerson()
	{
		cout << "姓名:" << this->m_name << "年龄:" << this->m_age << endl;
	}
	NameType m_name;
	AgeType m_age;
};
void test01()
{
	Person<string,int>p1("张三",10);//指定NameType为string,AgeType为int
	p1.ShowPerson();
}

2.类模板与函数模板的区别

2.1类模板没有自动类型推导的使用方式

2.2类模板可以在模板参数列表中设有默认参数

template<class NameType,class AgeType=int>//设置AgeType的类型默认为int
class Person
{
public:
	Person(NameType name,AgeType age)
	{
		this->m_name = name;
		this->m_age = age;
	}
	void ShowPerson()
	{
		cout << "姓名:" << this->m_name << "年龄:" << this->m_age << endl;
	}
	NameType m_name;
	AgeType m_age;
};
void test01()
{
	//Person p1("张三", 10)//错误,类模板没有自动类型推导的使用方式
	Person<string,int>p1("张三",10);//必须使用显示指定类型的方式,指定NameType为string,AgeType为int
	p1.ShowPerson();
}
void test02()
{
	Person<string>p2("李四",15); //类模板可以在模板参数列表中设有默认参数
	p2.ShowPerson();
}

3.类模板中成员函数调用的时机

3.1类模板中的成员函数并不是一开始就创建的,而是在模板调用时再生成

class Person1
{
public:
	void Show_Person1()
	{
		cout << "Show_Person1的调用" << endl;
	}
};
class Person2
{
public:
	void Show_Person2()
	{
		cout << "Show_Person2的调用" << endl;
	}
};
template<class T>
class My_Class
{
public:
	//类模板中的成员函数并不是一开始就创建的,而是在模板调用时再生成
	void func1(){obj.Show_Person1();}
	void func1() { obj.Show_Person1(); }
	T obj;
};
void test01()
{
	My_Class<Person1>p1;
	p1.func1();
	//p1.func2();//编译时才出错,说明函数调用时才会去创建成员函数
}

4.类模板实例化出的对象,向函数传参的方式

4.1指定传入类型————直接显示对象的数据类型

4.2参数模板化————将对象中的参数变成模板进行传递

4.3整个类模板化————将这个对象类型模板化进行传递

template<class NameType, class AgeType = int>//设置AgeType的类型默认为int
class Person
{
public:
	Person(NameType name, AgeType age)
	{
		this->m_name = name;
		this->m_age = age;
	}
	void ShowPerson()
	{
		cout << "姓名:" << this->m_name << " 年龄:" << this->m_age << endl;
	}
	NameType m_name;
	AgeType m_age;
};
//指定传入的类型
void Print_Person1(Person<string, int> &p)
{
	p.ShowPerson();
}
void test01()
{
	Person<string, int>p1("张三", 10);
	Print_Person1(p1);
}
//参数模板化

template<class T1,class T2>
void Print_Person2(Person<T1,T2>& p)
{
	p.ShowPerson();
	cout << "T1的类型为" << typeid(T1).name() << endl;
	cout << "T2的类型为" << typeid(T2).name() << endl;
}

void test02()
{
	Person<string, int>p2("李四", 15);
	Print_Person1(p2);
}
//整个类模板化
template<class T>
void Print_Person2(T & p)
{
	p.ShowPerson();
	cout << "T的类型为" << typeid(T).name() << endl;
}
void test03()
{
	Person<string, int>p3("王五", 14);
	Print_Person1(p3);
}

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值