C++入门——类、对象、运算符重载

C++具有完善的面向对象编程的功能。本文将以“点”这一对象相关方法的实现,讲解类的创建、函数的构造、运算符重载的方法,供初学者参考。

代码

#include 
#include 
using namespace std;

class point
{
     
public:
    point(){
     };                                      //无参构造函数,根据需要可自行编写有参构造函数
    point operator+(point &p);                      //对*的重载
    double operator*(point &p);                     //对+的重载
    double length();                                //计算该点到原点的距离
    friend istream &operator>>(istream &, point &); //对>>的重载,注意其重载的格式
    friend ostream &operator<<(ostream &, point &); //对<<的重载

private:
    double x;
    double y;
};

point point::operator+(point &p) //向量之和
{
     
    point P;
    P.x = x + p.x;
    P.y = y + p.y;
    return P;
}

double point::operator*(point &p) //内积
{
     
    return (x * p.x + y * p.y);
}

istream &operator>>(istream &input, point &p) //重载>>
{
     
    input >> p.x >> p.y;
    return input;
}

ostream &operator<<(ostream &output, point &p) //重载<<
{
     
    output << '(' << p.x << ',' << p.y << ')';
    return output;
}

double point::length() //向量长度
{
     
    return (sqrt(x * x + y * y));
}

double angle(point p1, point p2) //计算两个点所代表向量的余弦值
{
     
    double len1, len2;
    len1 = p1.length();
    len2 = p2.length();
    return ((p1 * p2) / (len1 * len2));
}

int main()
{
     

    double len, dotProduct, Angle;
    point p1, p2, p3;
    cout << "first point:";
    cin >> p1;
    cout << "second point:";
    cin >> p2;
    p3 = p1 + p2;
    dotProduct = p1 * p2;
    len = p3.length();
    Angle = angle(p1, p2);
    cout << "the new point:" << p3 << endl;
    cout << "length:" << len << endl;
    cout << "dotproduct:" << dotProduct << endl;
    cout << "cosine:" << Angle << endl;
    return 0;
}

你可能感兴趣的:(c++,算法,面向对象编程)