<<重载

ww911ff 2009-06-15 10:40:40
大侠,请帮帮忙!

定义point类,有数据成员x和y,使得以下main函数可以准备运行。
int main()
{
point p1(3,4),p2(5,6),p3;
p3=p1+p2;
cout<<p1<<”+”<<p2<<”=”<<p3<<endl;
//期望输出:(3,4)+(5,6)=(8,10)
++p3 ;
cout<<p3<<endl ; // 期望输出:(9,11)
return 0 ;
...全文
49 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
askcyg 2009-06-15
  • 打赏
  • 举报
回复
宏定义应该也可以吧:
#define p1 (p1.x,p1.y)
#define p2 (p2.x,p2.y)
#define p3 (p3.x,p3.y)
coreyao1988 2009-06-15
  • 打赏
  • 举报
回复

#include <iostream>
using namespace std;

class Point
{
friend ostream& operator<<(ostream& out,const Point& rhs);
friend Point operator+(const Point& lhs,const Point& rhs);
public:
Point(int x = 0,int y = 0);
public:
Point& operator++();
private:
int m_x;
int m_y;
};

ostream& operator<<(ostream& out,const Point& rhs)
{
out << "(" << rhs.m_x << "," << rhs.m_y << ")";
return out;
}

Point operator+(const Point& lhs,const Point& rhs)
{
Point result(lhs);
result.m_x += rhs.m_x;
result.m_y += rhs.m_y;
return result;
}

Point::Point(int x, int y)
{
m_x = x;
m_y = y;
}

Point& Point::operator ++()
{
++this->m_x;
++this->m_y;
return *this;
}


int main()
{
Point p1(3,4),p2(5,6),p3;
p3=p1+p2;
cout <<p1 <<"+" <<p2 <<"=" <<p3 <<endl;
//期望输出:(3,4)+(5,6)=(8,10)
++p3 ;
cout <<p3 <<endl ; // 期望输出:(9,11)
return 0 ;
}
seu_05104106 2009-06-15
  • 打赏
  • 举报
回复
外部定义就可以了,看bjarne的书吧,在中间部分
ostream& operator<<(ostream& os,const point& pt){
os<<"("<<pt.x<<","<<pt.y<<")";
return os;
}

65,211

社区成员

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

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