c++类模板对象做函数参数的三种传入方式

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

三种传入方式:

1.指定传入的类型—直接显示对象的数据类型(广泛)
2.参数模板化—将对象中的参数变为模板进行传递
3.整个类模板化—将这个对象类型 模板化进行传递
示例:

#include<iostream>
#include<string>
using namespace std;
template<class Nametype,class Agetype>
class Person
{
public:
	Person(Nametype name, Agetype age)
	{
		this->n_Name = name;
		this->n_Age = age;
	}
	void Show()
	{
		cout << "name:" << this->n_Name << endl;
		cout<< "age:"<< this->n_Age << endl;
	}
public:
	Nametype n_Name;
	Agetype n_Age;
};
//1.指定传入的类型
void Print(Person<string, int>& p)
{
	p.Show();
}
void test()
{
	Person<string, int> p1("lining", 19);
	Print(p1);
	cout << "---------------------------" << endl;
}
//2.参数模板化
template<class T1,class T2>
void Print2(Person<T1, T2>& p)
{
	p.Show();
	cout << "T1的类型为" << typeid(T1).name() << endl;
	cout << "T2的类型为" << typeid(T2).name() << endl;
	
}
void test2()
{
	Person<string, int> p1("lining", 19);
	Print2(p1);
	cout << "---------------------------" << endl;
}
//3.整个类模板化
template<class T>
void Print3(T& p)
{
	cout << "T的类型为" << typeid(T).name() << endl;
	p.Show();
}
void test3()
{
	Person<string, int> p1("lining", 19);
	Print3(p1);
	cout << "---------------------------" << endl;
}
int main()
{
	test();
	test2();
	test3();
	return 0;
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值