C++学习笔记46:模板与群体数据

时间:2025-04-03 11:03:32

函数模板

创建一个通用功能的函数,支持多种不同的形参;简化重载函数的函数体设计;

语法形式

template <模板参数表>

函数定义:
模板参数表的内容:
类型参数:class(或typename)标识符

常量参数:类型说明符,标识符

模板参数:template<参数表>class 标识符

例子:

template <class T> void outputArray(const T* array, int count){}

类模板

类模板的作用:

使用类模板使用户可以为类声明一种模式,使得类中的某些数据成员,某些成员函数的参数

某些成员函数的返回值,能取得任意的类型(包括基本数据类型和用户自定义类型)

类模板的声明

类模板template<模板参数表> class 类名 {类成员声明};

如果要在类模板外定义成员函数,采用如下形式:

template <模板参数表> 类型名 类名 <模板参数标识符列表>::函数名(参数表)

#include <iostream>
#include <cstdlib> using namespace std;
struct Student
{
int id;
float gpq;
}; template <class T>
class Store {
//类模板实现对任意类型进行存取
private:
T item;
bool haveValue;
public:
Store();
T &getElem();
void putElem(const T &x);
}; template <class T>
Store<T>::Store():haveValue(false) {} template <class T>
T &Store<T>::getElem()
{
//
return item;
} template <class T>
void Store<T>::putElem(const T &x)
{
//
} int main()
{
Store<int> s1, s2;
s1.putElem();
s2.putElem(-);
Student g = { , };
Store<Student> s3;
s3.putElem(g);
Store<double>d;
d.getElem();
}

线性群体的概念:
群体是由多个数据元素组成的集合体,分为:线性群体和非线性群体

非线性群体不用位置顺序来标识元素

在线性群体中,可以按照访问元素的不同方法分为直接访问、顺序访问,和索引访问;

数组类模板

动态数组由一系列位置连续的,任意数量相同类型的元素组成;

判断是否越界:

assert(n>=0 &&n<size);

指针转换运算符的作用

#include <iostream>
using namespace std; void read(int *p, int n)
{
for (int i = ; i < n; i++)
{
cin >> p[i];
}
} int main()
{
int a[];
read(a, );
return ;
}
//上述的例子可以实现指针转化,而以下的例子不行,因此需要指针转换运算符
#include <iostream>
#include "Array.h" void read(int *p, int n)
{
for (int i = ; i < n; i++)
{
cin >> p[i];
}
} int main()
{
Array<int> a();
read(a, );
return ;
}