将非类库分离为标头和实现的方法
way to separate non-class library into header and implementation
假设有一个名为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;
}
}
假设您的标头中有多个命名空间或嵌套命名空间,如下所示:
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;}
}
命名空间中的所有声明将放在一起。因此,在命名空间内调试和跳转将很容易。
此外,大多数开源项目使用第二次实现
相关文章:
- 实现无开销push_back的最佳方法是什么
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 这是实现图形的坏方法吗
- 在 c++ 中实现嵌套循环的更短方法吗?
- 如何实现 Front() 方法以返回模板化双向链表C++的第一个元素?
- 如何在从抽象基派生的类中实现相同的方法?
- C++数组队列实现方法错误
- 有没有一种通用的方法来实现不变量
- 'using namespace'实现细节的便捷方法(仅标头库)?
- 使用非递归插入方法实现 AVL 树
- C ++类型特征:确保子类实现方法
- 实现基于数字值(正、负、零)的条件表达式的最佳方法
- 在C++上实现高斯赛德尔迭代方法
- C++方法实现:是否可以避免每次都键入类名?
- 如何知道C2259 VS 2017错误未实现哪种方法?
- C++强制在子类中实现方法,但具有不同的签名
- 避免在每个派生类中重新实现方法调用
- C :执行模板类型实现方法
- 在C++中实现方法时继承不起作用
- 还有更好的实现方法吗?