假设您的标题中有多个命名空间或嵌套命名空间:
namespace test{
namespace subtest{
int Foo(int);
//many other functions go here
} //namespace subtest
} //namespace test
还有
namespace test1{
int Foo(int);
}
namespace test2{
int Bar(int);
}
在这些情况下,您应该始终使用 Second implementation,因为它使您的代码更具可读性和易于调试。
第一个:
#include "test.hpp"
int test::subtest::Foo(int x){return x;}
//many other goes here
看随着每次定义函数的嵌套增加,你需要编写函数的完全指定名称(再次重复命名空间)。
第二个:
#include "test.h"
namespace test{
namespace subtest{
int Foo(int x){return x;}
//other go here
}
}
这解决了命名空间名称重复问题,您也可以轻松地重构事物。要调试或重构命名空间的内容,只需跳转到它的第一个声明并更改内容。您还可以折叠单个命名空间下的代码。 (使用大多数 ide)让你的代码更漂亮。
同样适用于多个命名空间
第一个:
#include "test.hpp"
int test1::Foo(int x){return x;}
int test2::Bar(int x){return x;}
调试事情变得多么困难。此外,如果在两个命名空间下出现相同的函数名称,您将有很好的调试时间。
第二个:
#include "test.hpp"
namespace test1{
int Foo(int x){return x;}
}
namespace test2{
int Bar(int x){return x;}
}
命名空间内的所有声明都将放在一起。所以命名空间内的调试和跳转会很容易。
大多数开源项目也使用第二个实现