开发者社区> 问答> 正文

如何实现这个C++点类呢?

设计点类CMyPoint , 可以实现以下代码:
CMyPoint p1,p2,p3;
cin>>p1>>p2; //输入: 4,2 1,2
p3 = p1 + p2;
cout<p3 = p1 – p2 ;
cout<p3 = p1++;
cout<cout<<”++”<++p1 ;
cout<其中,点类的+运算的含义:
两个点的横坐标相加 得到 和的横坐标,
两个点的纵坐标相加 得到 和的纵坐标。
点了的-运算的含义:
被减数的横坐标 减去 减数的横坐标 得到 差的横坐标,
被减数的纵坐标 减去 减数的纵坐标 得到 差的纵坐标

展开
收起
a123456678 2016-03-05 13:04:21 1951 0
1 条回答
写回答
取消 提交回答
  • class CMyPoint
    {
    friend istream& operator>>(istream& cin, CMyPoint& pt);
    friend ostream& operator<<(ostream& cout, const CMyPoint& pt);
    friend CMyPoint operator+(const CMyPoint& point1, const CMyPoint& point2);
    friend CMyPoint operator-(const CMyPoint& point1, const CMyPoint& point2);
    public:
    CMyPoint() : m_x(0), m_y(0) {}
    CMyPoint(int x, int y) : m_x(x), m_y(y){}
    CMyPoint(const CMyPoint& point)
    {
    m_x = point.m_x;
    m_y = point.m_y;
    }
    CMyPoint& operator=(const CMyPoint& point)
    {
    m_x = point.m_x;
    m_y = point.m_y;
    return *this;
    }
    CMyPoint& operator+=(const CMyPoint& point)
    {
    m_x += point.m_x;
    m_y += point.m_y;
    return *this;
    }
    CMyPoint& operator-=(const CMyPoint& point)
    {
    m_x -= point.m_x;
    m_y -= point.m_y;
    return *this;
    }
    private:
    int m_x;
    int m_y;
    };
    
    istream& operator>>(istream& cin, CMyPoint& pt)
    {
    cin>>pt.m_x;
    cin>>pt.m_y;
    return cin;
    }
    
    ostream& operator<<(ostream& cout, const CMyPoint& pt)
    {
    cout<<"("<<pt.m_x<<","<<pt.m_y<<")";
    return cout;
    }
    
    CMyPoint operator+(const CMyPoint& point1, const CMyPoint& point2)
    {
    CMyPoint pt;
    pt.m_x = point1.m_x + point2.m_x;
    pt.m_y = point2.m_y + point2.m_y;
    return pt;
    }
    CMyPoint operator-(const CMyPoint& point1, const CMyPoint& point2)
    {
    CMyPoint pt;
    pt.m_x = point1.m_x - point2.m_y;
    pt.m_y = point1.m_y - point2.m_y;
    return pt;
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    CMyPoint pt1;
    CMyPoint pt2;
    CMyPoint pt3;
    cin>>pt1>>pt2;
    pt3 = pt1 + pt2;
    cout<<pt3<<endl;
    return 0;
    }

    输入: 2 2 3 3
    输出:(5,6)

    2019-07-17 18:53:12
    赞同 展开评论 打赏
问答分类:
C++
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载