假设有一个名为test的库,标题“ test.hpp”如下所示:
namespace test
{
int myfun(int a);
}
关于实现,哪种风格更好?
#include"test.hpp"
int test::myfun(int a){
return a*a;
}
或
#include"test.hpp"
namespace test
{
int myfun(int a){
return a*a;
}
}
答案 0 :(得分:1)
假设您的标头中有多个名称空间或嵌套名称空间:
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实现,因为它使您的代码更具可读性且易于调试。
第一个:
#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
}
}
这解决了名称空间名称重复的问题,您还可以轻松地重构事物。要调试或重构名称空间的内容,只需跳转到它的第一个声明并进行更改即可。您还可以将代码折叠在单个名称空间下。 (使用大多数方法)使您的代码更漂亮。
类似地用于多个名称空间
第一个:
#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;}
}
名称空间中的所有声明将在一起。因此,在名称空间中进行调试和跳转将很容易。
大多数开源项目也使用第二种实现方式