鱼C论坛

 找回密码
 立即注册
查看: 3970|回复: 2

友元定义问题,不知哪里错了。请大家帮忙。

[复制链接]
发表于 2012-10-23 07:44:05 | 显示全部楼层 |阅读模式
1鱼币
//成员操作符
#include<iostream>

using namespace std;

class Point{
int x,y;
public:
   void set(int a,int b){x=a,y=b;}
   Point operator+(const Point& d)
          {
          Point s;
          s.set(x+d.x,y+d.y);
          return s;
          }

   friend ostream& operator<<(ostream& o ,const Point& d);
};

  inline friend ostream& operator<<(ostream& o ,const Point& d)
{
  return o<<"("<<d.x<<","<<d.y<<")\n";
}


int main()
{
   Point s,t;
   s.set(2,5);
   t.set(3,1);
   cout<<s+t;



  return 0;
}


//[Error] 21: error: can't initialize friend function `operator<<'
//[Error] 21: error: friend declaration not in class definition

小甲鱼最新课程 -> https://ilovefishc.com
发表于 2012-10-23 07:44:06 | 显示全部楼层
  1. #include<iostream>

  2. using namespace std;

  3. //由于VC6有BUG,在VC6下要加这两行,VS2003及以上版本不要
  4. class Point;
  5. ostream& operator<<(ostream& o ,const Point& d);

  6. class Point{
  7. int x,y;
  8. public:
  9.    void set(int a,int b){x=a,y=b;}
  10.    Point operator+(const Point& d)
  11.           {
  12.           Point s;
  13.           s.set(x+d.x,y+d.y);
  14.           return s;
  15.           }

  16.    friend ostream& operator<<(ostream& o ,const Point& d);
  17. };

  18.   //inline friend ostream& operator<<(ostream& o ,const Point& d)
  19. ostream& operator<<(ostream& o ,const Point& d)
  20. {
  21.   return o<<"("<<d.x<<","<<d.y<<")\n";
  22. }


  23. int main()
  24. {
  25.    Point s,t;
  26.    s.set(2,5);
  27.    t.set(3,1);
  28.    cout<<s+t;



  29.   return 0;
  30. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2012-10-23 09:44:48 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-11-15 20:17

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表