使用模板函数实现一个复数类,熟悉模板函数的使用:
(1)在类的内部实现
#include <iostream>
using namespace std;
template <typename T>
class Complex
{
friend ostream & operator<< <T>(ostream &out, Complex c)
{
out << c.a << "+" << c.b << endl;
return out;
}
public:
Complex(T a, T b)
{
this->a = a;
this->b = b;
}
Complex operator+ (Complex &c)
{
Complex tem(a+c.a,b+c.b);
return tem;
}
private:
T a;
T b;
};
int main()
{
Complex<int> c1(1, 2), c2(3, 4);
Complex<int> c3 = c1 + c2;
cout << c3 << endl;
system("pause");
return 0;
}
(2)在类的外部实现(在一个.cpp文件)
#include <iostream>
using namespace std;
template <typename T>
class Complex
{
friend ostream & operator<< <T> (ostream &out, Complex &c);//注意此处<T>位置,若无<T>则报错
public:
Complex(T a, T b);
Complex operator+ (Complex &c);
Complex operator- (Complex &c);
private:
T a;
T b;
};
template <typename T>
Complex<T>::Complex(T a, T b)
{
this->a = a;
this->b = b;
}
template <typename T>
Complex<T> Complex<T>::operator+ (Complex<T> &c)
{
Complex tem(a + c.a, b + c.b);
return tem;
}
template <typename T>
Complex<T> Complex<T>::operator- (Complex<T> &c)
{
Complex tem(a-c.a,b-c.b);
return tem;
}
template <typename T>
ostream & operator<< (ostream &out, Complex<T> &c)
{
out << c.a << " + " << c.b;
return out;
}
int main()
{
Complex<int> c1(1,2);
Complex<int> c2(3, 4);
Complex<int> c3 = c1 + c2;
Complex<int> c4 = c2 - c1;
cout << c3 << endl;
cout << c4 << endl;
system("pause");
return 0;
}
需特别注意重载<<操作符时用到了友元函数,此时必须在operator<<后加上<T>,否则无法编译通过
不可以滥用友元函数(不是使用友元函数重载<< >>的情况),否则会产生错误,此时必须在类的前面添加类的前置声明以及函数的前置声明:
template <typename T>
class Complex;
template <typename T>
Complex<T> mySub(Complex<T>&c1, Complex<T>&c2);
同时在类的内部的声明必须写成:
friend Complex<T> mySub<T>(Complex<T>&c1, Complex<T>&c2);
友元函数的实现写成:
template <typename T>
Complex<T> mySub<T>(Complex<T>&c1, Complex<T>&c2)
{
Complex<T> tem(c1.a - c2.a,c1.b - c2.b);
return tem;
}
友元函数的调用写成:
Complex<int> c5 = mySub<int>(c2, c1);
(3)所有函数都写在类的外部(.h和.cpp分开)
.h文件
#pragma once
#include <iostream>
using namespace std;
template <typename T>
class Complex
{
friend ostream & operator<< <T> (ostream &out, Complex &c);//注意此处<T>位置,若无<T>则报错
public:
Complex(T a, T b);
Complex operator+ (Complex &c);
Complex operator- (Complex &c);
private:
T a;
T b;
};
.cpp文件:
#include "Complex.h"
template <typename T>
Complex<T>::Complex(T a, T b)
{
this->a = a;
this->b = b;
}
template <typename T>
Complex<T> Complex<T>::operator+ (Complex<T> &c)
{
Complex tem(a + c.a, b + c.b);
return tem;
}
template <typename T>
Complex<T> Complex<T>::operator- (Complex<T> &c)
{
Complex tem(a - c.a, b - c.b);
return tem;
}
template <typename T>
ostream & operator<< (ostream &out, Complex<T> &c)
{
out << c.a << " + " << c.b;
return out;
}
main文件:
#include "Complex.cpp"//注意此处引入的是.cpp文件
int main()
{
Complex<int> c1(1,2);
Complex<int> c2(3, 4);
Complex<int> c3 = c1 + c2;
cout << c3 << endl;
system("pause");
return 0;
}
注意引入文件时引入的是.cpp文件,否则会报找不到函数
(4)模板函数中的静态变量
不同类型各自使用自己的静态变量