這是我寫的用於開始使用類模板的代碼。如何調用此類程序中涉及類模板的單參數構造函數?
#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;'重新開始。從長遠來看,這將節省大量時間。 –