结构体应用示例——点操作函数

对平面上的点的操作的函数及应用

题目: 点的常用操作包括设置点的位置,获取点的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的引用传递,表示此形式参数是一个常量,在函数中只能引用不能修改。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值