編译器首次遇到该文件时,名称COORDIN_H_没有定义(我们根据include文件名来选择名称,并加
上一些下划线,以创建一个在其他地方不太可能被定义的名称)。在这种情况下,编译器将查看#ifndef和
#endif之间的内容(这正是我们希望的),并读取定义COORDIN_H_的一行。如果在同一个文件中遇到其
他包含coordin.h的代码,編译器将知道COORDIN_H_已经被定义了,从而跳到#endfi后面的一行上。注
意,这种方法并不能防止编译器将文件包含两次,而只是让它忽略除第一次包含之外的所有内容。大多数
标准C和C++头文件都使用这种防护(guarding)方案。
程序清单9.2 file1.cpp
// filel.cpp -- example of a three-file program
#include <iostream>
#include "coordin.h" // structure templates, function prototypes
using namespace std;
int main()
rect rplace:
polar pplace;
cout << "Enter the x and y values: ":
while (cin >> rplace.x >> rplace.y) // slick use of cin
pplace - rect_to_polar (rplace):
show_polar (pplace):
cout << "Next two numbers (q to quit): ";
cout << "Bye!\n":
return 0:
程序清单9.3 file2.cpp
// file2.cpp -- contains functions called in filel.cpp
#include <iostream>
Vinclude <cmath>
Finclude "coordin.h" // structure templates, function prototypes
// convert rectangular to polar coordinates
polar rect_to_polar (rect xypos)
using namespace std:
polar answer:
answer.distance =
sqrt (xypos.x * xypos.x + xypos. y * xypos.y);
answer.angle - atan2 (xypos.y, xypos.x);
return answer:
-
// returns a polar structure
// show polar coordinates. converting angle to degrees
void show_polar (polar dapos)
using namespace std:
const double Rad_to_deg - 57.29577951:
cout << "distance = " << dapos.distance:
cout << ", angle = " << dapos.angle * Rad to deg: