函数模板与类模板

函数模板

//函数模板实现char int数组排序
//函数模板本质:类型参数化
//函数模板机制:两次编译
#include <iostream>
using namespace std;

template <typename T,typename T1>
void mySort(T *myarray, T1 size)
{
	T1 i, j;
	T tmp;
	for (i = 0; i < size; i++) {
		for (j = i + 1; j < size; j++) {
			if (myarray[i] > myarray[j]) {
				tmp = myarray[i];
				myarray[i] = myarray[j];
				myarray[j] = tmp;
			}
		}
	}
}

template <typename T, typename T1>
void myPrint(T *myarray, T1 size)
{
	T1 i;
	for (i = 0; i < size; i++) {
		cout << myarray[i] << " ";
	}
	cout << endl;
}

int main01()
{
	int myarray[] = { 90,50,48,2,16,78,25,3,9,1 };
	int size = sizeof(myarray) / sizeof(*myarray);
	mySort<int, int>(myarray, size);
	myPrint<int, int>(myarray, size);

	char mystring[] = "agriyumvc953sdfg7";
	int len = strlen(mystring);
	mySort<char, int>(mystring, len);
	myPrint<char, int>(mystring, len);
	return 0;
}

类模板继承

//类模板 派生 1 普通类 2派生类
#include <iostream>
using namespace std;

template <typename T>
class A
{
public:
	A(T a)
	{
		this->a = a;
	}
	void printA()
	{
		cout << "a: " << a << endl;
	}
protected:
	T a;
};
//派生普通类,子类从模板类继承的时候,需要让编译器知道 父类的数据类型具体是什么
class B : public A<int>
{
public:
	B(int a, int b) :A<int>(a)
	{
		this->b = b;
	}
	void printB()
	{
		cout << "a: " << a << " b: " << b << endl;
	}
private:
	int b;
};
//派生 派生类,两个模板具体类型都暂不知道
template <typename T>
class C : public A<T>
{
public:
	C(T a, T c) :A<T>(a)
	{
		this->c = c;
	}
	void printC()
	{
		//cout << "a: " << a << " c: " << c << endl;	//此时a类型不确定无法输出?
		cout << "c: " << c << endl;
	}
protected:
	T c;
};


int main02()
{
	B b1(1, 2);
	b1.printB();
	//A<double> a1(2.3);
	C<int> c1(2,3);
	c1.printC();
	c1.printA();
	return 0;
}

类模板函数在类外部

//总结:友元函数只用来进行 左移 右移操作符重载,不要滥用,特别是在类模板中
#include <iostream>
using namespace std;

//模板函数在 类内部 或 类外部 或.h和.cpp分开
template <typename T>	//类模板
class Complex
{
	friend ostream& operator<<<T>(ostream& out, Complex& c3);	//重载<<
	//重要:模板类中友元函数在类外定义需要在声明时在函数名后加<T>
public:
	Complex(T a, T b);
	void printCom();
	Complex operator+(Complex& c2);	//重载+
		
private:
	T a;
	T b;
};

template <typename T>
Complex<T>::Complex(T a, T b)	//类模板里面的构造函数
{
	this->a = a;
	this->b = b;
}

template <typename T>
void Complex<T>::printCom()
{
	cout << "a: " << a << " b: " << b << endl;
}

//因为类模板类型是不确定的,所以在类外都要带<T>,函数体内属于类内部,<T>可带可不带
//检查需不需要带<T>,主要检查函数三要素:名称 参数 返回值
template <typename T>
Complex<T> Complex<T>::operator+(Complex<T>& c2)	//重载+
{
	Complex tmp(a + c2.a, b + c2.b);
	return tmp;
}

template <typename T>
ostream& operator<<(ostream& out, Complex<T>& c3)	//重载<<
{
	out << c3.a << "+" << c3.b << "i" << endl;
	return out;
}

int main()
{
	Complex<int> c1(1, 2);
	Complex<int> c2(3, 4);
	Complex<int> c3 = c1 + c2;
	cout << c3;
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值