这是我为开始使用类模板而编写的代码。
#include<iostream>
using namespace std;
template<class T>
class Complex
{
T *real,*imag;
public:
Complex(T a)
{
real=new T;
imag=new T;
*real=a;
*imag=0;
}
Complex(T a,T b)
{
real=new T;
imag=new T;
*real=a;
*imag=b;
}
Complex()
{
real=new T;
imag=new T;
*real=0;
*imag=0;
}
template<class R>
friend ostream& operator<<(ostream &out,Complex<R> &C);
template<class R>
friend istream& operator>>(istream &in,Complex<R> &C);
template<class R>
friend Complex<R> operator +(Complex<R> a,Complex<R> b);
};
template<class R>
ostream& operator<<(ostream &out,Complex<R> &C)
{
out<<"The number is "<<*C.real<<"+"<<*C.imag<<"i"<<endl;
return out;
}
template<class R>
istream& operator>>(istream &in,Complex<R> &C)
{
cout<<"Enter the number ";
in>>*C.real>>*C.imag;
return in;
}
template<class R>
Complex<R> operator +(Complex<R> a,Complex<R> b)
{
Complex<R> temp;
*temp.real=*a.real+*b.real;
*temp.imag=*a.imag+*b.imag;
return temp;
}
int main()
{
Complex<float> C1,C2(4.2,6.8),C3,C4;
C1=5;
C3=3+C1;
C4=C2+C3;
cout<<C1;
cout<<C2;
cout<<C3;
cout<<C4;
}
这段代码一切正常,除了当我尝试使用像“3+C2”这样的整数值时它显示错误。如果在不使用模板的情况下考虑相同的代码 '3+C2' 调用友元函数 operator+(Complex a,Complex b) 并且 3 被复制到调用单参数构造函数的对象 a 中,并且 3 将被分配给实部复杂类。使用类模板时如何做到这一点?使用类模板时,如何将数字传递给 operator+() 函数而不是 Complex 对象时调用单参数构造函数?