首页 > 代码库 > C++实现Point类

C++实现Point类

程序代码

#include <iostream>

using namespace std;

class Point//点类
{
public:
    //使用初始化表初始化点类
    Point(double a = 0, double b = 0):x(a), y(b){}
    double getX();//得到x坐标
    double getY();//得到y坐标

    //重载<<实现点的坐标的输出
    friend ostream& operator<<(ostream &output, Point &p);

protected:
    double x;//x坐标
    double y;//y坐标
};

//得到x的值
double Point::getX()
{
    return x;
}

//得到y的值
double Point::getY()
{
    return y;
}

//重载<<实现点的坐标的输出
ostream& operator<<(ostream &output, Point &p)
{
    output<<"("<<p.x<<","<<p.y<<")"<<endl;

    return output;
}


void main()
{
    //定义两个点对象
    Point p1(2.5, 3.7), p2(4.2, 6.3);

    //输出两个点的坐标
    cout<<"p1:"<<p1;
    cout<<"p2:"<<p2;

    system("pause");
}


执行结果


C++实现Point类