这是我写的用于开始使用类模板的代码。如何调用此类程序中涉及类模板的单参数构造函数?
#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'的模板的情况下考虑相同的代码,则调用朋友函数操作符+(复杂a,复合b),将3复制到调用单个参数构造函数的对象a,将3分配给复杂的类。如何使用类模板时发生同样的情况?如何在使用类模板时将数字传递给operator +()函数而不是Complex对象时调用单参数构造函数?
@πάνταῥεῖ错误出现在+运算符函数中。导致错误的整数值导致错误,因为单参数构造函数未被调用。我需要知道如何在使用类模板时使用C2 = 3 + C1。谢谢 – hcoder
你的代码从骨头上是有严重缺陷的。停止使用原始指针,新手入门。 –
您应该删除大部分代码,并从'T real,imag;'重新开始。从长远来看,这将节省大量时间。 –