名称空间

p266

名称空间不能用于代码块中;

默认下名称空间中声明的名称的链接性为外部。

在开发程序时使用多个文件时,一种有效的组织策略是,使用头文件来定义用户的类型,为操作用户类型的函数提供函数原型;并将函数定义放在一个独立的源代码文件中。头文件和源代码文件一起定义和实现了用户定义的类型及其使用方式。最后,将main()和其他使用这些函数的函数放在第三个文件中。

因此,可以将程序分成三部分:

1)头文件:包含结构声明和使用这些结构的函数的原型

2)源代码文件:包含与结构有关的函数的代码

3)源代码文件:包含调用与结构相关的函数的代码

给出一个例子:

a.h

#if !defined(A_A)
#define A_A

struct student
{
    char number[20];
    int scole;
};
void input(student & , const char *, int);
void show(const student &);

#endif // A_A

a.cpp

#include <iostream>
#include <cstring>
#include "a.h"  //包含头文件,使用"namesp.h"而不用<namesp.h>的原因是:使用后者,编译器将在存储标准头文件的主机系统的文件系统中查找;使用前者,编译器将首先查找当前的工作目录或源代码的目录(或其他目录,这取决于编译器)。如果没有找到,则将在标准位置查找。
using namespace std;
void input(student & a, const char * b, int c)
{
    strcpy(a.number,b);
    a.scole = c;
}
void show(const student & a)
{
    cout<<"number: "<<a.number<<endl;
    cout<<"scole: "<<a.scole<<endl;
}

b.cpp

#include <iostream>
#include "a.h"  //包含头文件
using namespace std;
int main()
{
    student a;
    input(a,"Jack Ma",100);
    show(a);
    return 0;
}

 

posted @ 2022-03-17 19:18  SanFranciscoo  阅读(38)  评论(0编辑  收藏  举报