#include<iostream>
using namespace std;
template<typename T>
class CComplex // CComplex<int>
{
public:
CComplex(T r = T(), T i = T())
:mreal(r), mimage(i){}
//前置和后置++运算符的重载
CComplex& operator++()
{
++mreal;
++mimage;
return *this;
}
CComplex operator++(int)
{
return CComplex(mreal++, mimage++);
}
private:
T mreal;
T mimage;
//template<typename T>加上这个是一个类对多个友元函数,没有意义的
//友元函数声明为模板函数必须在重载的运算符后面加上类型T
friend ostream& operator<< <T>(ostream &os, const CComplex<T> &obj);
friend CComplex<T> operator+<T>(const CComplex<T> &lhs,
const CComplex<T> &rhs);
};
template<typename T>
ostream& operator<<(ostream &out, const CComplex<T> &src)
{
out << "real:" << src.mreal << " image:" << src.mimage;
return out;
}
template<typename T>
CComplex<T> operator+(const CComplex<T> &lhs,
const CComplex<T> &rhs)
{
return CComplex<T>(lhs.mreal + rhs.mreal,
lhs.mimage + rhs.mimage);
}
//特例化模板
template<>
CComplex<int> operator+<int>(const CComplex<int> &lhs,
const CComplex<int> &rhs)
{
return CComplex<int>(lhs.mreal + rhs.mreal,
lhs.mimage + rhs.mimage);
}
int main(int argc, char* argv[])
{
CComplex<int> comp1;
comp1++;
++comp1;
cout << comp1 << endl;
CComplex<int> comp2(20, 20);
CComplex<int> comp3 = comp1 + comp2;
cout << comp3 << endl;
//comp3 = comp1 + 20;
// ::operator+(comp1, 20) //int => CComplex<T>
//comp3 = ::operator+<int>(comp1, 20);//CComplex<type> => CComplex<T>
//无法从“int”为“const CComplex<T> &”推导 模板 参数
cin.get();
return 0;
}