C++第5章数据的共享与保护.pptVIP

  • 12
  • 0
  • 约1.47万字
  • 约 69页
  • 2016-08-15 发布于重庆
  • 举报
C第5章数据的共享与保护

例如,声明一个命名空间NS: namspace SomeNS { class SomeClass; void SomeFun (); } 则引用标识符的方式如下, NS:: SomeClass obj1; NS:: SomeFun (); 可以用using来指定命名空间或命名空间中的标识符,具体格式如下: using 命名空间名::标识符名 using namespace 命名空间名 例如,经过以下声明: using SomeNS :: SomeClass; using namespace SomeNS; 回顾: using namespace std; 命名空间std中所有标识符都可直接引用 在新的C++标准程序库中,所有标识符都声明在命名空间std中,头文件都不使用扩展名 两类特殊的命名空间 -----全局命名空间和匿名命名空间 //file1.cpp #include iostream using namespace std; int i=3; void next(); void other(); int main() { i++; next(); coutiendl; } void next() { i++; other(); } 4. defined操纵符 格式:defined(标识符) #ifndef MYHEAD_H #define MYHEAD_H ……… #endif 注意:可能出现的头文件的多次包含! //main.cpp #include file1.h #include file2.h int main() { … } //file1.h #include head.h … //file2.h #include head.h … 使用条件编译后的头文件 //head.h #ifndef HEAD_H #define HEAD_H class Point { … } … #endif 例 5-10(续) //文件3,主函数,5_10.cpp #include Point.h #include iostream using namespace std; int main() { Point a(4, 5); //定义对象a,其构造函数回使count增1 cout Point A: a.getX() , a.getY(); Point::showCount(); //输出对象个数 ? Point b(a); //定义对象b,其构造函数回使count增1 cout Point B: b.getX() , b.getY(); Point::showCount(); //输出对象个数 ? return 0; } * 5.6多文件结构和编译预处理命令 —— 5.6.1 C++的一般组织结构 例5-10(续) * #include point.h #include iostream …… #include point.h #include iostream …… point.cpp class Point { …… point.h 5_10.cpp 可执行文件5_10.exe point.obj 5_10.obj 编译 编译 连接 连接 系统运行库 连接 iostream 包含 包含 包含 包含 系统文件 5.6多文件结构和编译预处理命令 —— 5.6.1 C++的一般组织结构 外部变量 如果一个变量除了在定义它的源文件中可以使用外,还能被其它文件使用,那么就称这个变量是外部变量。 文件作用域中定义的变量,缺省情况下都是外部变量,但在其它文件中如果需要使用这一变量,需要用extern关键字加以声明。 * 5.6多文件结构和编译预处理命令 —— 5.6.2 外部变量与外部函数 外部函数 在所有类之外声明的函数(也就是非成员函数),都是具有文件作用域的。 这样的函数都可以在不同的编译单元中被调用,只要在调用之前进行引用性声明(即声明函数原型)即可。也可以在声明函数原型或定义函数时用extern修饰,其效果与不加修饰的缺省状态是一样的。 * 5.6多文件结构和编译预处理命令 —— 5.6.1 C++的一般组织结构 将变量和函数限制在编译单元内 使用匿名的命名空间:在匿名命名空间中定义的变量和函数,都不会暴露给其它的编译单元。 namespace { //匿名的命名空间 int n; void f() { n++; } } 这里被“namespace { …… }”

文档评论(0)

1亿VIP精品文档

相关文档