c语言中给文件命名空间,C在源文件中使用命名空间

给定标题“n.h”:

namespace n{

extern void f();

}

以下没有在命名空间n中定义f()(从这里开始,我将它称为n :: f:

#include "n.h"

using namespace n;

void f(){ }

如果您尝试在任何地方引用n :: f,则会出现链接时错误.以上定义了全局命名空间中的f.这确实定义了n :: f:

#include "n.h"

void n::f(){ }

这也是:

#include "n.h"

namespace n{

void f(){ }

}

但有一个缺点,如果你错误输入名称或签名,你将添加一个新的函数到命名空间并留下void n :: f()undefined,导致半恼人的链接时错误.

当涉及到课程时,事情会有所不同:

namespace n{

class c{

void f();

};

extern c operator + (const c&, const c&); // I'll use Matthieu M.'s example

}

这没关系,因为没有全局c:

#include "n.h"

using namespace n;

void c::f(){ }

但是,如果您尝试添加两个c,则以下将导致链接时错误,原因与第一次尝试定义n :: f()的原因相同:

#include "n.h"

using namespace n;

c operator + (const c &a, const c &b){ /* blah blah */ } // define global +

此方案还会导致链接时错误(或者甚至是编译错误,具体取决于定义:: c :: f的位置):

class c{ // a global c, defined in some header somewhere

void f();

};

#include "n.h"

using namespace n;

void c::f(){ } // define the global c::f (a possible redefinition) and n::c::f remains undefined!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值