运算符 乘号 重载 用来计算复数的问题 ??

doudouyeah 2009-06-10 06:37:57
程序如下

#include<iostream>
using namespace std;
class complex
{
public:
complex()
{real=0;image=0;}
complex(int r,int m)
{real=r;image=m;}
complex operator* (complex &a);
void print();
private:
int real;
int image;
};

void complex::print()
{cout<<real<<"+"<<image<<endl;}

complex complex::operator* (complex A,complex B)
{complex a;
a.real=A.real*B.image-A.image*B.real;
a.image=A.real*B.image+A.image*B.real
return a;
}

void main()
{complex v1(2,3);
complex v2(4,5);
complex v3;
v3=v1*v2;
cout<<v3<<endl;
}


错误提示如下 求高手指点。。。

c:\program files\microsoft visual studio\myprojects\ss\dfs.cpp(21) : error C2511: '*' : overloaded member function 'class complex (class complex,class complex)' not found in 'complex'
c:\program files\microsoft visual studio\myprojects\ss\dfs.cpp(4) : see declaration of 'complex'
c:\program files\microsoft visual studio\myprojects\ss\dfs.cpp(32) : error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class complex' (or there is no acceptable conversion)
Error executing cl.exe.

...全文
259 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
kang315 2009-06-10
  • 打赏
  • 举报
回复
#include <iostream>
using namespace std;
class complex
{
public:
complex()
{real=0;image=0;}
complex(int r,int m)
{real=r,image=m;}
friend complex operator*(complex A,complex B); //这个
void print();
private:
int real;
int image;
};

void complex::print()
{cout <<real <<"+" <<image <<endl;}

complex operator*(complex A,complex B) //zhe
{complex a;
a.real=A.real*B.real-A.image*B.image;
a.image=A.real*B.image+A.image*B.real;
return a;
}

void main()
{complex v1(2,3);
complex v2(4,5);
complex v3;
v3=v1*v2;
v1.print();
v2.print();
v3.print();
//cout <<v3 <<endl;
} 程序 这样改后 貌似可以用了
Jalien 2009-06-10
  • 打赏
  • 举报
回复
lz注意自己调试,报错其实很明显了。我改好了,lz琢磨一下。

#include <iostream>
using namespace std;

class complex
{
public:
complex(){
real=0;
image=0;
}
complex(int r,int m){
real=r;
image=m;
}
friend complex operator*(const complex& A,const complex& B);
friend ostream& operator<<(ostream& os,complex& a);
void print();
private:
int real;
int image;
};

void complex::print() {
cout <<real <<"+" <<image <<endl;
}

complex operator*(const complex& A,const complex& B) {
return complex(A.real*B.image-A.image*B.real,A.real*B.image+A.image*B.real);
}

ostream& operator<<(ostream& os,complex& a){
os<<a.real <<"+" <<a.image <<endl;
return os;
}
void main() {
complex v1(2,3);
complex v2(4,5);
complex v3;
v3=v1*v2;
cout <<v3 <<endl;
}

64,636

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧