c++模版

1.什么是模版?

生活中比如常用的ppt模版,年终报告模版等,共有的特性通用性、不能直接使用、不是万能的

2.c++中的模版

c++处理面向对象编程思想还有面向泛型编程,面向泛型编程主要用的技术就是模版,模版有函数模版和类模版

3.函数模版

建立一个通用的函数,返回值类型和形参类型不具体指定,是通用类型,使用的时候才确定。

比如交换两个整型数字函数

如果要交换两个浮点型,又得写一个函数

此时可以定义一个用于交换两个数的函数模版,但是具体数的类型不知道

#include <iostream>
using namespace std;

template<typename T>//告诉编译器紧跟着的是一个函数模版 T是通用的数据类型
void myswap(T &a,T &b) {
	T temp= a;
	a = b;
	b = temp;
}

int main() {
	int a = 10;
	int b = 20;
	//调用模版函数第一种方式
	myswap(a, b);
	//调用模版函数第二种方式,支出T具体类型
	myswap<int>(a, b);
	cout << "a="<<a<<"b="<< b;
}

注意:

1.上面的typename可以替换成关键字class

2.调用的时候T必需明确什么数据类型

3.函数模版也可重载,这点就可以为特定类型提供具体化的模版

class person {
public:
	int age;
	string name;
};

template<typename T>
int compare(T& a, T& b) {
	if (a == b) {
		return 1;
	}
	else {
		return -1;
	}
};
//具体化模版规则,指出数据类型
template<> int compare(person &a, person &b) {
	if (a.age== b.age) {
		return 1;
	}
	else {
		return -1;
	}
}


int main() {
	person p;
	p.age = 10;
	person p1;
	p1.age = 20;
	//优先调用具体化模版
	compare(p, p1);
}

4.学习模版主要是为了使用stl中的模版,而不是自己写模版

4.类模版

一个通用的类,成员变量的数据类型不确定

template<class ageType,class nameType>//ageType和nameType是通用类型
class person {
public:
	person(ageType age, nameType name) {
		this->age = age;
		this->name = name;
	}
public:
	ageType age;
	nameType name;
	void say() {
		cout << "年龄:"<<age << "姓名:" << name;
	}
};


int main() {
	person<int, string> p(10, "lisi");
	p.say();
}

类模版在模版的参数列表中可以有默认的参数类型,如下

template<class ageType,class nameType=string>

注意:

1.普通函数中的成员函数一开始就创建,但是类模版只有调用才创建

2.类模版对象作为函数参数传递方式有以下三种

#include <iostream>
#include <string>
using namespace std;

template<class ageType,class nameType=string>
class person {
public:
	person(ageType age, nameType name) {
		this->age = age;
		this->name = name;
	}
public:
	ageType age;
	nameType name;
	void say() {
		cout << "年龄:"<<age << "姓名:" << name;
	}
};
//1.第一种
void test1(person<int, string>& p) {
	p.say();
}
//2.第二种参数模板化 但是调用的时候给出
template<class T1 ,class T2>
void test2(person<T1, T2>& p) {
	p.say();
}
//3.第三种整个类模板化 但是调用的时候给出
template<class T>
void test3(T& p) {
	p.say();
}

int main() {
	person<int, string> p(10, "lisi");
	test1(p);
	test2(p);
	test3(p);
}

3.类模版与继承

template<class ageType,class nameType=string>
class person {

};
//子类
class man :public person<int, string> {

};

4.类模版中的函数在类外实现

#include <iostream>
#include <string>
using namespace std;

template<class ageType,class nameType=string>
class person {
public:
	person(ageType age, nameType name);//类内声明
public:
	ageType age;
	nameType name;
	void say();
};
//类外实现
template<class T1,class T2>
person<T1,T2>::person(T1 age, T2 name) {
	this->age = age;
	this->name = name;
}
int main() {
	person<int, string> p(10, "lisi");
	
}

5.类模版中成员函数分文件编写问题以及解决

发布了260 篇原创文章 · 获赞 112 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/qq_34491508/article/details/103298658