friend使用

anbyice 2008-11-12 11:28:11

#include <iostream>
using namespace std;
class Point
{
int x,y;

public:
void set(int a,int b);
Point operator+(Point& d);
friend ostream& operator<<(ostream&o,Point&d);

};
inline ostream& operator<<(ostream&o,Point&d)
{
return o<<'('<<d.x<<','<<d.y<<')'<<endl;
}
void Point::set(int a,int b){x=a,y=b;}
Point Point::operator +(Point&d)
{
Point s;
s.set(x+d.x,y+d.y);
return s;
}
int main()
{
Point s,t;
s.set(2,5);
t.set(3,1);
cout<<s+t;
}
各位大侠,为什么编译时老是说我在‘ostream’中不能访问私有数据成员啊?我都用关键字friend声明了啊?那个用了inline是不是相当于这个函数就算是成员函数了啊,还是只是效率好了一点?
...全文
101 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
anbyice 2008-11-14
  • 打赏
  • 举报
回复
不好意思啊,我的分比较少,所以没能全给各位加分,只能在这里在此谢谢大家了!
anbyice 2008-11-14
  • 打赏
  • 举报
回复
谢谢大侠!
anbyice 2008-11-14
  • 打赏
  • 举报
回复
网上搜到过类似我这样的问题,说重新打开vc6重新运行就可以了,我这个试了还是不行,既然各位大侠都没问题那么看来是我的vc安装有问题了啊。在此先谢过各位热心的大侠!
ronliu 2008-11-12
  • 打赏
  • 举报
回复
声明一个函数为inline,只是建议编译器按照内联的方式编译它,但是编译器不一定照做。
要看编译器怎么实现的啦。
有的编译器,即使你不声明为内联,但如果编译器认为函数很小,直接展开的代价比较小,那么它有可能在编译时直接展开了。
yanhang1589 2008-11-12
  • 打赏
  • 举报
回复
VS2005运行通过且得到你想要的结果。
inline是内联函数,由于先申明了为friend函数,所以不是类的成员函数。
cyj626 2008-11-12
  • 打赏
  • 举报
回复
up
mujiok2003 2008-11-12
  • 打赏
  • 举报
回复
code is ok.
Longinc 2008-11-12
  • 打赏
  • 举报
回复

class Point
{
int x,y;
public:
void set(int a,int b);
Point operator+(Point& d);
friend ostream& operator <<(ostream&o,Point&d);

};
inline ostream& operator <<(ostream&o,Point&d)
{
return o <<'(' <<d.x <<',' <<d.y <<')' <<endl;
}
void Point::set(int a,int b){x=a,y=b;}
Point Point::operator +(Point&d)
{
Point s;
s.set(x+d.x,y+d.y);
return s;
}
int main()
{
Point s,t;
s.set(2,5);
t.set(3,1);
cout <<s+t;
system("pause");
}

VC6.0 下通过
hhyttppd 2008-11-12
  • 打赏
  • 举报
回复
我用 vs2005没有你说的问题。
帅得不敢出门 2008-11-12
  • 打赏
  • 举报
回复


class Point
{
int x,y;

public:
void set(int a,int b);
Point operator+(Point& d);
friend ostream& operator <<(ostream&o,Point&d);

};
inline ostream& operator <<(ostream&o,Point&d)
{
return o <<'(' <<d.x <<',' <<d.y <<')' <<endl;
}

void Point::set(int a,int b){x=a,y=b;}
Point Point::operator +(Point&d)
{
Point s;
s.set(x+d.x,y+d.y);
return s;
}
int main()
{
Point s,t;
s.set(2,5);
t.set(3,1);
Point tmp = s+t;
cout <<tmp;
}


那个用了inline是不是相当于这个函数就算是成员函数了啊,还是只是效率好了一点?
不是 效率要看编译器给不给你内联了.
chary8088 2008-11-12
  • 打赏
  • 举报
回复
LZ用的应该是VC编译器的版本比较低!!
这个没有语法问题的
编译器的问题!
overbai 2008-11-12
  • 打赏
  • 举报
回复
VC6.0下没有问题!
overbai 2008-11-12
  • 打赏
  • 举报
回复
VC6.0下没有问题!

65,211

社区成员

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

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