目錄
程序分爲三部分
- 頭文件:包含結構聲明和使用這些結構的函數原型
- 源代碼文件:包含與結構相關的函數原型代碼
- 源代碼文件:包含main,調用與結構相關的代碼
頭文件包含的內容:
- 函數原型
- 使用#define 或者const 定義的符號常量
- 結構聲明
- 類聲明
- 模板聲明
- 內聯函數
coordin.h
// coordin.h -- 結構和函數聲明
// structure templates
// 直角座標系--極座標系的轉換
#ifndef COORDIN_H_
#define COORDIN_H_
struct polar //極座標
{
double distance;
double angle;
};
struct rect //直角座標系
{
double x;
double y;
};
// prototypes
polar rect_to_polar(rect xypos);
void show_polar(polar dapos);
#endif
file1.cpp
// file1.cpp -- example of a three file program
#include<iostream>
#include"coordin.h"
using namespace std;
int main()
{
rect rplace;
polar pplace;
cout << "請輸入x和y的值:" << endl;
while (cin>>rplace.x>>rplace.y)
{
pplace = rect_to_polar(rplace);
show_polar(pplace);
cout << "下一組x,y的值(輸入q退出):" << endl;
}
cout << "老鐵,下次再見!" << endl;
return 0;
}
file2.cpp
// file2.cpp -- 包含file1.cpp的函數
#include<iostream>
#include<cmath>
#include"coordin.h"
//本函數轉換直角座標系到極座標系
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;
}
// 顯示極座標,轉換角度到弧度
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;
cout << " degrees\n";
}
運行結果
多個庫連接問題
9.1節