【发布时间】:2016-04-06 20:25:22
【问题描述】:
这是我为开始使用类模板而编写的代码。
#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 对象,如何调用单参数构造函数?
【问题讨论】:
-
@πάντα ῥεῖ + 运算符函数中出现错误。传递整数值会导致错误,因为未调用单参数构造函数。我需要知道如何在使用类模板时使用 C2=3+C1。谢谢
-
您的代码存在严重缺陷。停止使用原始指针和
new作为初学者。 -
您应该删除大部分代码并从
T real,imag;重新开始。从长远来看,这将节省大量时间。
标签: c++ constructor class-template