携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第22天,点击查看活动详情
1.类模板实例化对象概述
-
类模板也可以实例化对象的,如果这个对象想向一个函数中传递,当作一个参数进行传递。 学习目标:
-
类模板实例化出的对象,向函数传参的方式
2.类模板向函数传参的方式
一共有三种传入方式:
- 指定传入的类型 --- 直接显示对象的数据类型
不是通过传进去的参数去调用里面的函数成员,而是把参数传到一个函数中,然后让他作为一个实参,在他的函数体内部去调用类中的成员函数,类模板的对象作为函数参数
- 参数模板化 --- 将对象中的参数变为模板进行传递 传入的数据类型
- 整个类模板化 --- 将这个对象类型 模板化进行传递
3.指定传入的类型 --- 直接显示对象的数据类型
#include<iostream>
#include <fstream>
#include <string>
using namespace std;
//类模板
template<class N , class A >
class H
{
public:
H(N name, A age)
{
this->Name = name;
this->Age = age;
}
void h_idol()
{
cout << "name: " << this->Name << " age: " << this->Age << endl;
}
public:
N Name;
A Age;
};
void spr(H<string,int>&h01) {
h01.h_idol();
}
void test()
{
// 指定NameType 为string类型,AgeType 为 int类型
H<string,int> h01("道枝骏佑",19);
spr(h01);
}
int main() {
test();
system("pause");
return 0;
}
输出:
name: 道枝骏佑 age: 19 请按任意键继续. . .
4.参数模板化
template<class H1,class H2>
void spr(H<H1,H2>&h01) {
h01.h_idol();
cout << "H1的类型为: " << typeid(H1).name() << endl;
cout << "H2的类型为: " << typeid(H2).name() << endl;
}
void test()
{
// 指定NameType 为string类型,AgeType 为 int类型
H<string,int> h01("白敬亭",28);
spr(h01);
}
int main() {
test();
system("pause");
return 0;
}
输出:
name: 白敬亭 age: 28
H1的类型为: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >
H2的类型为: int
请按任意键继续. . .
5.模板
模板 是C++支持参数化多态的工具,使用模板可以使用户为类或者函数声明一种一般模式,使得类中的某些数据成员或者成员函数的参数、返回值取得任意类型。
模板是一种对类型进行参数化的工具;
通常有两种形式:函数模板和类模板;
函数模板针对仅参数类型不同的函数;
类模板针对仅数据成员和成员函数类型不同的类。