对平面上的点的操作的函数及应用
题目: 点的常用操作包括设置点的位置,获取点的x,y坐标,显示点的位置,计算两个点的距离。试定义点类型并实现这些函数。
代码清单:
# include<iostream>
# include<cmath>
using namespace std;
//创建结构体
struct pointT {
double x, y;
};
//函数声明
void setPoint(double x, double y, pointT& p);//设定点的坐标
double getX(const pointT& p);//获取x坐标
double getY(const pointT& p);//获取y坐标
void showPoint(const pointT& p);//显示点的位置
double distancePoint(const pointT& p1, const pointT& p2);//计算两个点之间的距离
//主函数
int main() {
pointT p1, p2;
setPoint(1, 1, p1);
setPoint(2, 2, p2);
cout << getX(p1) << " " << getY(p2) << endl;
showPoint(p1);
cout << "->";
showPoint(p2);
cout << "=" << distancePoint(p1, p2) << endl;
return 0;
}
void setPoint(double x, double y, pointT& p) {
p.x = x;
p.y = y;
}
double getX(const pointT& p) {
return p.x;
}
double getY(const pointT& p) {
return p.y;
}
void showPoint(const pointT& p) {
cout << "(" << p.x << "," << p.y << ")";
}
double distancePoint(const pointT& p1, const pointT& p2) {
return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}
运行结果如下:
在结构作为函数的参数时,结构体的传递和普通内置类型一样都是值传递,值传递的方式既浪费空间也浪费时间,因此常采用引用传递。
引用传递虽然提高了函数调用的效率,但也带来了安全隐患。因为在指针传递和引用传递中,形式参数和实际参数共享了同一块空间——对形式参数的修改就是对实际参数的修改,违背了值传递的原则。要解决这个问题,可以使用const的引用传递,表示此形式参数是一个常量,在函数中只能引用不能修改。