将 non-class 库分成 header 和实现的方法
way to separate non-class library into header and implementation
假设有一个名为 test 的库,header "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;
}
}
假设您的 header 中有多个名称空间或嵌套的名称空间:
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);
}
在这些情况下,您应该始终使用第二个实现,因为它使您的代码更具可读性和易于调试。
第一个:
#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;}
}
命名空间内的所有声明将在一起。因此命名空间内的调试和跳转会很容易。
而且大多数开源项目使用第二个实现
假设有一个名为 test 的库,header "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;
}
}
假设您的 header 中有多个名称空间或嵌套的名称空间:
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);
}
在这些情况下,您应该始终使用第二个实现,因为它使您的代码更具可读性和易于调试。
第一个:
#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;}
}
命名空间内的所有声明将在一起。因此命名空间内的调试和跳转会很容易。
而且大多数开源项目使用第二个实现