これは、クラス テンプレートを使い始めるために私が書いたコードです。
#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 が実数部分に割り当てられます。複雑なクラス。クラステンプレートが使用されているときに同じことを行うにはどうすればよいですか? クラステンプレートが使用されているときに、Complex オブジェクトの代わりに数値が operator+() 関数に渡されたときに単一引数コンストラクターを呼び出す方法は?