当前位置:嗨网首页>书籍在线阅读

21-传递结构的地址

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

7.6.3 传递结构的地址

假设要传递结构的地址而不是整个结构以节省时间和空间,则需要重新编写前面的函数,使用指向结构的指针。首先来看一看如何重新编写show_polar()函数。需要修改3个地方:

  • 调用函数时,将结构的地址(&pplace)而不是结构本身(pplace)传递给它;
  • 将形参声明为指向polar的指针,即polar *类型,由于函数不应该修改结构,因此使用了const修饰符;
  • 由于形参是指针而不是结构,因此应使用间接成员运算符(->),而不是成员运算符(句点)。

完成上述修改后,该函数如下所示:

// show polar coordinates, converting angle to degrees
void show_polar (const polar * pda)
{
    using namespace std;
    const double Rad_to_deg = 57.29577951;
    cout << "distance = " << pda->distance;
    cout << ", angle = " << pda->angle * Rad_to_deg;
    cout << " degrees\n";
}

接下来对rect_to_polar进行修改。由于原来的rect_to_polar函数返回一个结构,因此修改工作更复杂些。为了充分利用指针的效率,应使用指针,而不是返回值。为此,需要将两个指针传递给该函数。第一个指针指向要转换的结构,第二个指针指向存储转换结果的结构。函数不返回一个新的结构,而是修改调用函数中已有的结构。因此,虽然第一个参数是const指针,但第二个参数却不是。也可以像修改函数show_polar() 修改这个函数。程序清单7.13列出了修改后的程序。

程序清单7.13 strctptr.cpp

// strctptr.cpp -- functions with pointer to structure arguments
#include <iostream>
#include <cmath>
// structure templates
struct polar
{
    double distance;  // distance from origin
    double angle;      // direction from origin
};
struct rect
{
    double x; // horizontal distance from origin
    double y; // vertical distance from origin
};
// prototypes
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); // pass addresses
        show_polar(&pplace); // pass address
        cout << "Next two numbers (q to quit): ";
    }
    cout << "Done.\n";
    return 0;
}
// show polar coordinates, converting angle to degrees
void show_polar (const polar * pda)
{
    using namespace std;
    const double Rad_to_deg = 57.29577951;
    cout << "distance = " << pda->distance;
    cout << ", angle = " << pda->angle * Rad_to_deg;
    cout << " degrees\n";
}
// convert rectangular to polar coordinates
void rect_to_polar(const rect * pxy, polar * pda)
{
    using namespace std;
    pda->distance =
        sqrt(pxy->x * pxy->x + pxy->y * pxy->y);
    pda->angle = atan2(pxy->y, pxy->x);
}

注意: 有些编译器需要明确指示,才会搜索数学库。例如,较早的g++版本使用下面这样的命令行:

g++ structfun.C -lm

从用户的角度来说,程序清单7.13的行为与程序清单7.12相同。它们之间的差别在于,程序清单7.12使用的是结构副本,而程序清单7.13使用的是指针,让函数能够对原始结构进行操作。