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