怎么总是遇见这种问题?这次又是怎么回事?

wildcat1984 2003-12-10 11:25:00
#include <iostream>
using namespace std;
class my{
int i;
public:
my(int ii):i(ii){}
const my operator+(const my &b)const
{return my(i+b.i);}

const my operator-(const my &b)const
{return my(i-b.i);}

void print(ostream& os)
{os<<i<<endl;}
};
void main()
{ostream myos(cout);
my a(1);my b(2);my c(3);
my result=a+b-c;
result.print(myos);
}
这个没问题


#include <iostream.h>

class my{
int i;
public:
my(int ii):i(ii){}
friend const my operator+(const my &b,const my &c)const
{ return my(c.i+b.i);
}

friend const my operator-(const my &b,const my &c) const
{ return my(c.i-b.i);
}


void print(ostream& os)
{os<<i<<endl;}
};

void main()
{my a(1);my b(2);my c(3);
my result=a+b-c;
result.print(cout);
}
这个就不对,这次这两个友元为什么不能是const??
...全文
39 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
wildcat1984 2003-12-11
  • 打赏
  • 举报
回复
friend const my operator+(const my &b,const my &c)const
是这里,最后一个const不能加,否则就错,为什么?
sboom 2003-12-11
  • 打赏
  • 举报
回复
const 重载运算符??
hanyixin 2003-12-11
  • 打赏
  • 举报
回复

函数后面的const只能加在成员函数后面,表示不改变对象状态。

不能加在全局函数上。

70,037

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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