您的位置:首页 > 编程语言 > C语言/C++

C++ Primer Plus 第九章(单独编译)

2015-09-12 17:38 337 查看
详细请参考C++ Primer Plus 第九章(p301)

1单独编译
与其将结构声明加入到每一个文件中,不如将其放在头文件中,然后在每一个源代码文件中包含该头文件。这样,要修改结构声明时,只需要在头文件中做一次改动即可。另外,也可以将函数原型放在头文件中。因此,可以将原来的程序分成三部分:

第一,头文件:包含结构声明和使用这些结构的函数的原型。

第二,源代码文件:包含与结构有关的函数的代码。

第三,源代码文件:包含调用与结构相关的函数的代码。

头文件常常包含的内容:

1)函数原型;

2)使用#define或const定义的符号常量;

3)结构声明;

4)类声明;

5)模板声明;

6)内联函数

只需要将源代码文件加入到项目中,而不用加入头文件。这是因为#include指令管理头文件。另外,不要使用#include来包含源代码文件,这样做将导致多重声明。

注意:不要将头文件加入到项目列表中,也不要在源代码文件中使用#include来包含其他源代码文件。

2文件头管理
在同一个文件中只能将同一个文件包含一次。下面的片段意味着仅当以前没有使用预处理器编译指令#define定义名称COORDIN_H_时,才处理#ifndef和#endif之间的语句:

#ifndef COORDIN_H_

#define COORDIN_H_

... ...

#endif

如果在同一个文件中遇到其他包含coordin.h的代码,编译器将知道COORDIN_H_已经被定义了,从而跳到#endif后面的一行上。注意,这种方法并不能防止编译器将文件包含两次,而只是让它忽略除第一次包含之外的所有内容。

3程序代码例子
//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

//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";

}

//file2.cpp 源文件 主程序

#include <iostream>

#include "coordin.h"

using namespace std;

int main()

{

rect rplace;

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 numbers(q to quit): ";

}

cout<<"Bye!\n";

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: