0
点赞
收藏
分享

微信扫一扫

第五章 模板与群体数据(1)

zibianqu 2022-05-02 阅读 44
c++

引入

整数类型和浮点数类型求绝对值的算法,需要写两种重载函数吗?

函数模板

就像制造业的模板一样,设定一个模板,大体的事情就被框定了

基本数据类型 

如果可以推导出 T 是基本数据类型,那么一般的cout << 这类插入运算符没有问题

自定义数据类型

特别要注意处理插入运算符,需要重载该运算符,否则没有办法“替换”

示例:

template <class T>
void outputArray(const T *array, int count) {
    for(int i=0; i<cout; i++)
        cout << array[i] << " ";
    cout << endl;
}

// 使用部分
int a[8] = {1,2,3,4,5,6,7,8};
double b[8] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8};
char c[20] = "Welcome";

// 基本数据类型,可以自动推导出数据类型
outputArray(a, 8);
outputArray(b, 8);
outputArray(c, 20);

// 自定义类型,比如类,需要提供 << 运算符重载

注意事项 

类模板 

既然函数能做成模板,那么类为什么不可以呢?

模板的默认实参 

函数/类 模板可以有默认模板实参

template <typename T = double>

示例:

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

struct Student {
	int id;
	float gpa;
};

template <class T>
class Store {
private:
	T item;
	bool haveValue;
public:
	friend T;
	Store();
	T &getElem();
	void putElem(const T &x);
};

template <class T>
Store<T>::Store():haveValue(false) {}

template <class T>
T &Store<T>::getElem() {
	if(!haveValue) {
		cout << "No item present!" << endl;
		exit(1);
	}

	return item;
}

template <class T>
void Store<T>::putElem(const T &x) {
	haveValue = true;
	item = x;
}

int main() {
	using IntStore = Store<int>;        // 1
	IntStore s1, s2;
	s1.putElem(3);
	s2.putElem(-7);
	cout << s1.getElem() <<" " << s2.getElem() << endl;
	
	Student g = {1000, 23};
	Store<Student> s3;                  // 2
	s3.putElem(g);
	cout << "The student id is " << s3.getElem().id << endl;
	
	Store<double> d;
	cout << "Retrieving object D...";
	cout << d.getElem() << endl;
	
	return 0;
}

1):使用 using 方式可以定义别名

2):不实用 using 方式

再次说明,可以看作是 宏替换,但具体是编译器做替换动作,否则这个文件会出现重复定义类的情况,这也说明了不是简单 宏替换的做法

举报

相关推荐

第五章 模板与群体数据(2)

第五章

五,Eureka 第五章

第五章 方法与技巧

MySQL 第五章

第五章 列表

第五章 Tomcat

第五章总结

0 条评论