runsisi

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  45 随笔 :: 15 文章 :: 26 评论 :: 0 Trackbacks
定义全局外部变量:
在.cpp文件中定义一个命名namespace,然后在.h文件中extern,如:
在App的cpp文件中定义一个
namespace glb
{
int a,b;
//全部变量和函数
}
在APP的h文件中
namespace glb
{
extern int a,b;
//全部变量和函数
}
定义链接性为内部的全局变量使用匿名namespace.

示例代码如下:
1.namespace.h文件
#ifndef NAMESPACE_H_
#define NAMESPACE_H_
#include
<iostream>
namespace RUNSISI
{
    
class test
    {
    
public:
        test(){}
        
~test(){}
        
void print();
    };
    
namespace ms
    {    
        
extern const char* str;
    }
}

/*namespace ms
{
    extern const char* str;
}
*/
#endif
2.namespace1.cc
同时演示了名称空间嵌套
#include "namespace.h"
namespace RUNSISI
{
    
namespace ms
    {
        
const char* str="i love u.\n";
    }
}

namespace RUNSISI
{
    
void test::print()
    {
        std::cout
<<"hello namespace.\n";
    }
}
3.namespace.cc
使用名称空间,演示了使用匿名名称空间定义链接性为内部的全局变量
#include "namespace.h"
//using namespace ms;

namespace
{
    
int b;
}

int main()
{
    RUNSISI::test a;
    a.print();
    b
=0;
    
namespace mr=RUNSISI::ms;
    std::cout
<<mr::str;
    
return 0;
}


posted on 2009-03-27 13:48 runsisi 阅读(447) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理