当代码较多,工程较大时,可以将原来的程序分成3部分:1.头文件:包含结构声明和使用这些结构的函数原型(声明)。2.源代码文件:包含与结构有关的函数代码。3.源代码文件:包含调用与结构有关的函数的代码。
头文件包含的内容:1.函数原型。2.使用#define或const定义的符号常量。3.结构声明。4.类声明。5.模板声明。6.内联函数。
头文件"coordin.h"。同一个文件中只能将同一个头文件包含一次,为了避免不小心包含多次,使用编译指令#ifndef,例如以下代码,如果COORDIN_H_已经被定义了,则跳到#endif
#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
第3个源代码文件:包含调用与结构有关的函数代码
#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!" << endl;
return 0;
}
第2个源代码文件:包含与结构有关的函数代码
#include<iostream>//包含与结构有关的函数代码
#include<cmath>
#include"coordin.h"
using namespace std;
polar rect_to_polar(rect xypos)
{
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)
{
const double Rad_to_deg = 57.29577951;
cout << "distance=" << dapos.distance;
cout << ",angle=" << dapos.angle*Rad_to_deg;
cout << "degrees" << endl;
}
两个源代码文件和新的头文件编译链接,生成可执行程序。
如果有两个名字相同的变量,一个位于内部代码块,一个位于外部代码块,则内部代码块中新的定义将暂时屏蔽外部代码块中的代码。
静态持续变量:有3种链接性1.外部链接性(可在其他文件中访问)。2.内部链接性(只能在当前文件中访问)。3.无链接性(只能 在当前函数或代码块中访问)。外部链接性:代码块外声明。内部链接性:代码块外声明+static。无链接性:代码块内声明+static。
无链接性静态变量与自动变量不同的是,即使在函数没有被执行时,变量也存在。
多个文件使用同一个变量时,必须加extern,如extern int cat;
在代码块中有同名的局部变量时,若要访问全局变量,则必须使用作用域解析运算符::,如cout<<::cat;就是访问全局的cat,不是代码块中的cat。
静态变量只在第一次启用是被初始化,在以后的函数调用中,其值不会被初始化。
mutable:
struct Data
{
char name[30];
mutable int acesses;
};
int main()
{
const Data veep = { "GOOGLE",0 };
strcpy(veep.name, "hola");//不被允许,因为veep是常结构体
veep.acesses++;//可以,因为acesses声明了mutable
}
定位new运算符:能够指定要使用的位置,如下代码,记得加头文件<new>
#include<iostream>
#include<new>
using namespace std;
struct chaff
{
char dross[20];
int slag;
};
char buffer1[50];
char buffer2[100];
int main()
{
chaff*p1;
int *p2;
p1 = new(buffer1)chaff;//从buffer1中分配空间给chaff
p2 = new(buffer2)int[20];//从buffer2中分配空间给int[20]
}
定位new不能使用delete来释放内存,delete只能用来释放堆内存,定位new的内存不是堆内存。
名称空间:1.声明域:整个代码块。2.潜在作用域:从变量定义开始到结束,包括被屏蔽的。3.作用域:不包括被屏蔽的。
namespace Jack
{
double pail;
void fetch();
int pal;
struct Well{...};
}
namespace Jill
{
double bucket(double n) { ... };
double fetch;
int pal;
struct Hill{...};
}
名称空间可以是全局的,也可以位于另一个名称空间中,但不能位于代码块中。
Jack::pail=12.34, Jill::Hill mole ,Jack::fetch()。
using 编译指令和using声明的区别:声明使一个可用,编译使多个可用。using Jill::fetch; using namespace Jack。
尽量不要在头文件中使用using 编译指令。