和C语言一样,c++也允许甚至鼓励程序员将组件函数放在多个文件中进行单独编译,然后进行链接!
IDE:Dev c++,建立控制台工程
实例:将直角坐标系的数据转换成极坐标数据文件输出,分为三个文件,一个主函数文件,一个头文件(包含所需的结构的定义以及函数的原型),一个函数定义的文件。
主函数文件:
//文件名:main.cpp
#include<iostream>
#include"coordin.h"//本文件中的结构和函数在coordin.h中定义和使用原型
using namespace std;//名称空间
int main()
{
rect rplace;//直角坐标结构变量x and y
polar pplace;//极坐标结构变量
cout << "Enter the x and y values";
while(cin >> rplace.x >> rplace.y)//输入值
{
pplace = rect_to_polar(rplace);
show_polar(pplace);
cout << "next two number (q to quit):";
}
cout << "BYE!\n";
return 0;
}
头文件:
//文件名:coordin.h
#ifndef COORDIN_H_
#define COORDIN_H_
struct polar //极坐标数据
{
double distance;
double angle;
};
struct rect //直角坐标数据
{
double x;
double y;
};
//函数原型
polar rect_to_polar(rect xypos);
void show_polar(polar dapos);
#endif
函数定义文件:
//文件名为:函数定义.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 Red_to_deg = 57.29577951;//角度转换常数
cout << "distance = " << dapos.distance;
cout << ", angle = " << dapos.angle*Red_to_deg;
cout << "degrees\n";
}