【c++|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;
}
推荐阅读
- 霍乱时期的Python之路|【Leetcode】89. 格雷编码(Gray Code)
- 蓝桥杯|蓝桥杯每日一题(30)单词分析(python)
- LFU (最不经常使用算法)缓存
- python|蓝桥杯每日一题(29)成绩统计(python)
- 我用过的设计模式|我用过的设计模式(3)-- 观察者模式
- 欧拉定理与费马小定理
- QT|基于C++的Qt(一)概述
- 深度学习|正则化方法笔记
- kmeans|【ML31】Advanced K-means clustering algorithm