C++提高6:类模板对象做函数参数

本文介绍了C++中类模板实例化对象作为函数参数的三种方式:指定类型传入、参数模板化和整个类模板化。详细展示了每种方式的使用示例,并指出在实际应用中,指定类型传入的方式更为常见。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

类模板也是可以实例化对象的,因此类模板也可以做函数参数。

1、作用

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

2、一共有三种传入方式:

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

直接举个例子

#include<iostream>
#include<string>
using namespace std;
void test01();//函数的声明
int main()
{
	test01();
	system("pause");
	return 0;
}
//类模板对象做函数参数
template<class T1, class T2>//创建一个类模板
class person
{
public:
	T1 m_name;
	T2 m_age;
	person(T1 name, T2 age)//指定参数
	{
		this->m_name = name;
		this->m_age = age;
	}
	void showPerson()
	{
		cout << "name:" << this->m_name << endl;
		cout << "age: " << this->m_age << endl;
	}
};
void printPerson(person<string , int>&p)//将整个类模板作为参数传递进函数
{
	p.showPerson();//调用
}
void test01()
{
	person<string, int > p("孙悟空", 999);
	printPerson(p);//传参
}
参数模板化

直接举个例子

#include<iostream>
#include<string>
using namespace std;
void test02();
int main()
{
	test02();
	system("pause");
	return 0;
}
//类模板对象做函数参数
template<class T1, class T2>
class person
{
public:
	T1 m_name;
	T2 m_age;
	person(T1 name, T2 age)
	{
		this->m_name = name;
		this->m_age = age;
	}
	
	void showPerson()
	{
		cout << "name:" << this->m_name << endl;
		cout << "age: " << this->m_age << endl;
	}
};
/*以上的类的构建就不细说了*/
template <class T1, class T2>//将模板声明,否则下一句话将报错,编译器没办法识别T
void printPerson2(person<T1, T2>&p)//直接将参数模板化,不细分是int还是string,一律模板化为T。
{
	p.showPerson();
	cout << "T1的类型为: " << typeid(T1).name() << endl;
	cout << "T2的类型为: " << typeid(T2).name() << endl;
}
void test02()
{
	person <string, int >p("猪八戒", 90);
	printPerson2(p);
}

最后的结果是:

name:猪八戒
age: 90
T1的类型为: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >
T2的类型为: int
请按任意键继续. . .

可以看书,T1和T2的类型。

整个类模板化

直接上例子:

#include<iostream>
#include<string>
using namespace std;
void test03();
int main()
{
	test03();
	system("pause");
	return 0;
}
//类模板对象做函数参数
template<class T1, class T2>
class person
{
public:
	T1 m_name;
	T2 m_age;
	person(T1 name, T2 age)
	{
		this->m_name = name;
		this->m_age = age;
	}
	
	void showPerson()
	{
		cout << "name:" << this->m_name << endl;
		cout << "age: " << this->m_age << endl;
	}
};
template<class T>//直接将整个类模板化,传递的参数只整个的一个类模板
void printPerson3(T &p)
{
	cout << "T的类型为: " << typeid(T).name() << endl;
	p.showPerson();
}
void test03()
{
	person <string, int >p("唐僧", 30);
	printPerson3(p);
}

最后的结果是

T的类型为: class person<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,int>
name:唐僧
age: 30
请按任意键继续. . .

总结:

  • 通过类模板创建的对象,可以有三种方式向函数中进行传参
  • 使用比较广泛是第一种:指定传入的类型
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值