本人是学生、一个菜鸟,在努力学C++比较感兴趣,想请问高手一个问题
这是一个关于运算符重载,和输入输出重载的问题:
#include <iostream.h>
#include <iostream.h>
class Complex
{
public:
Complex(){}
Complex operator + (Complex &c2);
friend ostream& operator < < (ostream &, Complex &);
friend istream& operator > > (istream &, Complex &);
private:
double real;
double imag;
};
Complex Complex:: operator + (Complex &c2)
{
return Complex(real+ c2.real, imag + c2.imag);
}
ostream& operator < <(ostream& output, Complex &c)
{
output < < "( " < <c.real < < "+ " < <c.imag < < "i) " < <endl;
return output;
}
istream& operator > > (istream& input, Complex &c)
{
cout < < "input real part and imaginary part of complex number: ";
input> > c.real> > c.imag;
return input;
}
int main(void)
{
Complex c1,c2,c3;
cin> > c1> > c2;
c3 = c1 + c2;
cout < <c1 < <endl;
cout < <c2 < <endl;
cout < <c3 < <endl;
return 0;
}
--------------------Configuration: Cpp1 - Win32 Debug--------------------
Compiling...
Cpp1.cpp
F:\编程\TMP\Cpp1.cpp(21) : error C2661: 'Complex::Complex ' : no overloaded function takes 2 parameters
Error executing cl.exe.
Cpp1.exe - 1 error(s), 0 warning(s)
如果在类中加声明:Complex(double r, double i){};就不报错了
或把+的重载函数改下
声明成友元函数friend Complex operator + (Complex &c1,Complex &c2);用两个参数
定义的部分改为Complex operator + (Complex &c1,Complex &c2)
{
Complex c3;
c3.real = c1.real + c2.real;
c3.imag = c1.imag + c2.imag;
return c3;
}
也不报错
想请问下高手这是为什么??是不是return Complex(real+ c2.real, imag + c2.imag);产生了2义性啊
[解决办法]
不是的,原因就在于你没有将+函数声明位friend,如果你声明了 程序会调用你的+操作符
如果你没有声明你用+ 程序不会调用你的+操作符函数,所以就报错。
[解决办法]
Complex(){}//你只有一个构造函数啊,大哥,而且还是默认构造函数呢
我想问Complex(real+ c2.real, imag + c2.imag)这个怎么可以调用默认构造函数??!!
应该在类中再重载一个构造函数:Complex(double r, double i):real(r),imag(i){ }
这样就行了
[解决办法]
"return Complex(real+ c2.real, imag + c2.imag); "中的 "Complex(real+ c2.real, imag + c2.imag); "是调用构造函数,但却没有相应的构造函数供调用啊.
应该在类中再重载一个相应的构造函数.
[解决办法]
这是我修改完的代码,已经编译测试过了,对照一下你自己的,就能明白了。
#include <iostream>
using namespace std;
class Complex{
public:
Complex( double r=0, double i=0 );
Complex operator+( Complex &c2 );
friend ostream& operator < <( ostream &output, Complex &c );
friend istream& operator> > ( istream &input, Complex &c );
private:
double real;
double imag;
};
Complex::Complex( double r, double i )
{
real = r;
imag = i;
}
Complex Complex::operator+( Complex &c2 )
{
return Complex( real+c2.real, imag+c2.imag );
}
ostream& operator < <( ostream &output, Complex &c )
{
output < < "( " < <c.real < < "+ " < <c.imag < < "i) " < <endl;
return output;
}
istream& operator> > ( istream &input, Complex &c )
{
cout < < "input real part and imaginary part of complex number: ";
input> > c.real> > c.imag;
return input;
}
int main( void )
{
Complex c1,c2,c3;
cin> > c1> > c2;
c3 = c1 + c2;
cout < <c1 < <endl;
cout < <c2 < <endl;
cout < <c3 < <endl;
return 0;
}
[解决办法]
那个return语句实际是这样的:
Complex tmp;
tmp.real = this.real+ c2.real;
tmp.imag = this.imag + c2.imag;
return tmp;
只不过现在我们把这个tmp给省略了。我们实际上用了一个临时变量,这个变量在代码中没有体
现出来,而是由编译器在幕后为我们做这一切。