给定标题“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!