c++复数类 运算符重载问题

2024-12-23 07:08:42
推荐回答(2个)
回答1:

知道错在哪了
你不要在自动创建的头文件(stdafx.h)里写东西 自己重新建一个头文件和同名源文件 把你自己写的东西剪切过去 如:

新建 001.h
#include
class Complex
{
public:
Complex(float R=0,float I=0){real=R;imag=I;}
void SetComplex(float R,float I){real=R;imag=I;}
friend Complex operator +(Complex c1,Complex c2);
friend Complex operator -(Complex c1,Complex c2);
friend Complex operator *(Complex c1,Complex c2);
friend Complex operator /(Complex c1,Complex c2);
friend ostream& operator <<(ostream&,Complex&);
friend istream& operator >>(istream&,Complex& );
Complex& operator =( Complex& c);
void PrintComplex();
private:
float real;
float imag;
};

//001.cpp

#include "001.h"
template
T Test(T x,T y,T z)
{return x+y*z;}
Complex operator +(Complex c1,Complex c2)
{return Complex (c1.real+c2.real,c1.imag+c2.imag);}
Complex operator -(Complex c1,Complex c2)
{return Complex (c1.real-c2.real,c1.imag-c2.imag);}
Complex operator *(Complex c1,Complex c2)
{return Complex (c1.real*c2.real-c1.imag*c2.imag,-c1.real*c2.imag+c1.imag*c2.real);}
Complex operator /(Complex c1,Complex c2)
{return Complex (c1.real*c2.real+c1.imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag),(-c1.real*c2.imag+c1.imag*c2.real)/(c2.real*c2.real+c2.imag*c2.imag);}
Complex& Complex::operator =(Complex& c)
{c.real=real;c.imag=imag;return *this;}
void Complex::PrintComplex()
{cout<<"("<ostream& operator <<(ostream& cout,Complex& c)
{cout<<"("<istream& operator >>(istream& cin,Complex& c)
{cin>>c.real;
cin>>c.imag;
return cin;}

还有主文件里的这个 #include"stdafx.cpp" 删掉

回答2:

VC6?VC6.0对模板和友员支持不好。也没看,猜测可能是这个原因。。
你自己搜下看VC6.0与友员吧