关于网友提出的“ 泛型函数简易但难度极高的错误修改(简短程序代码,考验细心度)”问题疑问,本网通过在网上对“ 泛型函数简易但难度极高的错误修改(简短程序代码,考验细心度)”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:
问题: 泛型函数简易但难度极高的错误修改(简短程序代码,考验细心度)
描述: #include
using namespace std;
template< class T >
class Complex
{
public:
Complex( T& );
Complex( T&, T& );
Complex operator+(const Complex& ) const;
void write() const;
Complex();
private:
T& real;
T& imag;
};
Complex::Complex()
{
real = imag = 0.0;
}
void Complex::write() const
{
cout << real << " + " << imag << 'i';
}
Complex Complex::operator +(const Complex& u) const
{
Complex v( real + u.real,
imag + u.imag );
return v;
}
template< class T >
Complex::Complex(T& re, T& im)
{
real = re;
imag = im;
}
template< class T >
Complex::Complex(T& re)
{
real = re;
imag = 0.0;
}
int main(){
Complex c1( a1,b1 ),c2( a2,b2 ),c3;
cout << "请输入c1,c2的实部和虚部: " << endl;
cin << a1 << a2 << b1 << b2;
cout<< "c1= ";
c1.write();
cout << '\n';
cout << "c2= ";
c2.write();
cout << '\n';
c3=c1+c2;
cout << "c1+c2= ";
c3.write();
cout << '\n';
return 0;
}
这个泛型函数编译时
Complex::Complex()
{
real = imag = 0.0;
}
语句出错。望高手指点!
解决方案1: 跟泛型没啥关系吧
你的real和imag是引用,要放在初始化列表中初始化吧
以上介绍了“ 泛型函数简易但难度极高的错误修改(简短程序代码,考验细心度)”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/3018696.html