C++ namespace笔记
2012-08-31 17:36
162 查看
最近有一个移植项目,需要将Windows平台的一个项目移植到iOS平台,前提是Windows项目由多个动态库组成,是C和C++混合代码,不同的动态库中存在有相同的的文件名,变量名,函数名…。而iOS平台的应用只支持静态库,不支持动态库,也就是说必须把Windows项目所有动态库的代码整合到一个iOS工程中,那么重定义等问题就无法避免了。想了一个解决办法,就是利用namespace,已达到不用修改不同文件中同名变量和函数的目的(当然,文件名相同的就需要改文件名了,namespace解决不了这个问题)。但使用的时候还是发现了一个需要注意的地方,那就是namespace中的变量,具体解释见下面代码中的注释部分,范例如下:
例子中假设一共有5个文件,ClassOne.h, ClassOne.cpp, ClassTwo.h, ClassTwo.cpp,TestNamespace.cpp
代码如下:
ClassOne.h
ClassOne.cpp
ClassTwo.h
ClassTwo.cpp
TestNamespace.cpp
例子中假设一共有5个文件,ClassOne.h, ClassOne.cpp, ClassTwo.h, ClassTwo.cpp,TestNamespace.cpp
代码如下:
ClassOne.h
// ClassOne.h: interface for the CClassOne class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_CLASSONE_H__A95C3A2F_01CB_4791_9F19_26ECAEDE69D2__INCLUDED_) #define AFX_CLASSONE_H__A95C3A2F_01CB_4791_9F19_26ECAEDE69D2__INCLUDED_ namespace NamespaceClassOne{ #define MARCO_DEMO 1 extern int var; // 用extern指定这不是定义. // 不能定义具有外部链接的变量。因为有多个编译单元话,在链接的时候会找到多个定义,链接器无法确定应该链接到哪个定义上因此报错。 const int constVal = 1; // 但可以定义常量,因为常量是内部链接。 int Func(); } #endif // !defined(AFX_CLASSONE_H__A95C3A2F_01CB_4791_9F19_26ECAEDE69D2__INCLUDED_)
ClassOne.cpp
// ClassOne.cpp: implementation of the CClassOne class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ClassOne.h" namespace NamespaceClassOne{ int var; int Func() { return 1; } }
ClassTwo.h
// ClassTwo.h: interface for the CClassTwo class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_CLASSTWO_H__7119FA49_C5C4_454B_8C1E_6560783FBF94__INCLUDED_) #define AFX_CLASSTWO_H__7119FA49_C5C4_454B_8C1E_6560783FBF94__INCLUDED_ namespace NamespaceClassTwo{ #define MARCO_DEMO 1 extern int var; int Func(); }; #endif // !defined(AFX_CLASSTWO_H__7119FA49_C5C4_454B_8C1E_6560783FBF94__INCLUDED_)
ClassTwo.cpp
// ClassTwo.cpp: implementation of the CClassTwo class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ClassTwo.h" namespace NamespaceClassTwo{ int var; int Func() { return 2; } }
TestNamespace.cpp
// TestNamespace.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "ClassOne.h" #include "ClassTwo.h" using namespace NamespaceClassOne; int main(int argc, char* argv[]) { int a = Func(); var = a; int b = NamespaceClassTwo::Func(); NamespaceClassTwo::var = b; return 0; }
相关文章推荐
- C++学习笔记--new和namespace
- C++学习笔记1-namespace是什么东西?
- namespace笔记----C++
- c++ primer plus阅读笔记10---定位new using namespace
- C++学习笔记之---namespace的使用
- [More Effective C++ 学习笔记]效率
- C++温故笔记(二)
- c++内存管理学习笔记结束语
- 设计模式C++学习笔记之十一(Bridge桥梁模式)
- 设计模式C++学习笔记之十九(State状态模式)
- C++学习笔记之数据类型
- C++primer plus 第11-12章笔记
- 【C++】学习笔记三十八——函数指针
- 【菜鸟C++学习笔记】21.引用
- C++内存管理学习笔记(7)
- C++面试笔记--字符串
- C++学习笔记31——类的基础概念
- C++引用和指针的区别 —— 笔记
- C++学习笔记---const 关键字
- C++语法细节笔记