如果想要传递结构的地址,而不是整个结构以节省时间,那么就应该像本例这么写代码。
首先看看如何重写show_polar()函数。需要修改三个地方:
- 调用函数时,传递结构的地址(&pplace)而不是结构本身(pplace);
- 将形参声明为指向polar的指针,即polar*类型,由于函数不应该修改结构,加上const修饰符
- 由于形参是指针而不是结构,因此需要使用间接成员运算符(->),而不是成员运算符(.)。
完成修改够,该函数代码如下:
//显示polar的坐标,转换弧度为度数
void show_polar(const polar *pda)
{
using namespace std;
const double Rad_to_deg = 57.29577951;//这个是一弧度等于57.29577951的意思
cout << "distance=" << pda->distance;
cout << ",angle=" << pda->angle * Rad_to_deg;
cout << " degreses\n";
}
原来的rect_to_polar函数返回一个结构,因此修改的工作更复杂一些。需要将两个指针传递给该函数,第一个指针指向需要转换的坐标结构,第二个指针指向存储转换结果的polar结构。函数不返回一个新的结构,而实修改调用函数中已有的结构。第一个参数是const指针,第二个参数却不是。修改后的代码如下:
//转换 直角坐标到极坐标
void rect_to_polar(const rect* pxy, polar* pda)
{
using namespace std;
// polar answer;
pda->distance = sqrt(pxy->x * pxy->x + pxy->y * pxy->y);
pda->angle = atan2(pxy->y, pxy->x);
}
下面是全部的代码。
用指针实现了例子7.12 相同的功能。
// Chapter7.6_Example7.12strtfun.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <cmath>
struct polar
{
double distance;//到原点的距离
double angle;//到原点的方向
};
struct rect
{
double x;//x坐标
double y;//y 坐标
};
/*不用指针的时候的 原型
polar rect_to_polar(rect xypos);
void show_polar(polar dapos);*/
//使用指针的时候的原型
void rect_to_polar(const rect* pxy,polar * pda);
void show_polar(const polar* pda);
int main()
{
using namespace std;
rect rplace;
polar pplace;
cout << "Enter the x and y values:";
while (cin >> rplace.x >> rplace.y)
{
rect_to_polar(&rplace,&pplace);
show_polar(&pplace);
cout << "Next two numbers(q to quit):";
}
cout << "Done.\n";
return 0;
}
//转换 直角坐标到极坐标
void rect_to_polar(const rect* pxy, polar* pda)
{
using namespace std;
// polar answer;
pda->distance = sqrt(pxy->x * pxy->x + pxy->y * pxy->y);
pda->angle = atan2(pxy->y, pxy->x);
}
//显示polar的坐标,转换弧度为度数
void show_polar(const polar *pda)
{
using namespace std;
const double Rad_to_deg = 57.29577951;//这个是一弧度等于57.29577951的意思
cout << "distance=" << pda->distance;
cout << ",angle=" << pda->angle * Rad_to_deg;
cout << " degreses\n";
}