为什么通不过编译?

wangzeba 2004-08-16 11:39:33
为什么通不过编译?
#include<iostream.h>
class complex
{
private:
int real;
int imag;
public:
complex(int r=0,int i=0)
{
real=r;
imag=i;
}
friend complex operator +(complex &,complex &);
void show()
{
cout<<real<<"+"<<imag<<"i";
}
};

friend complex operator + (complex &a,complex &b)
{
int r1=a.real+b.real;
int i1=a.imag+b.imag;
return complex(r1,i1);
}

void main()
{
complex x(2,3),y(4,5),z;
z=x+y;
z.show();
}

...全文
136 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
sinhence 2004-08-16
  • 打赏
  • 举报
回复
include<iostream>
using namespace std;
class complex
{
private:
int real;
int imag;
public:
complex(int r=0,int i=0)
{
real=r;
imag=i;
}
complex(complex &cc)
{
real=cc.real;
imag=cc.imag;
}
complex operator +(complex &a)//重载运算符不正确
{
int r,i;
r=real+a.real;
i=imag+a.imag;
return complex(r,i);
}
complex& operator=(complex &a)//没有重载赋值运算符
{
real=a.real;
imag=a.imag;
return *this;
}
void show()
{
cout<<real<<"+"<<imag<<"i";
}
};

void main()
{
complex x(2,3),y(4,5),z;
z=x+y;
z.show();
}
rorot 2004-08-16
  • 打赏
  • 举报
回复
// class complex
// useage -: test class complex
#include <iostream>

class Complex
{
public:
Complex(int r=0,int i=0):real_(r), imag_(i){}
friend Complex operator +( const Complex &, const Complex &);
void Show() { std::cout << real_ << "+" << imag_ << "i"; }

private:
int real_;
int imag_;
};

Complex operator + (const Complex &a,const Complex &b)
{
int r1 = a.real_ + b.real_;
int i1 = a.imag_ + b.imag_;
return Complex(r1, i1);
}

int main()
{
Complex x(2,3),y(4,5),z;
z = x + y;
z.Show();

return 0;
}
RookieStar 2004-08-16
  • 打赏
  • 举报
回复
bianliuwei(C++一辈子)说的对。

是语法问题。
friend在类外的定义不用写friend这个关键字。
steel007 2004-08-16
  • 打赏
  • 举报
回复
friend complex operator +(complex &,complex &);
建议改为
friend complex operator +(const complex &,const complex &);

其于的同楼上
bianliuwei 2004-08-16
  • 打赏
  • 举报
回复
楼上说的没错,不过楼主是在类里面申明的,不过在外面函数定义的时候那个friend去掉就OK了!
hellwolf 2004-08-16
  • 打赏
  • 举报
回复
只能在类中声明友元函数

64,651

社区成员

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

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