将非类库分离为标头和实现的方法

way to separate non-class library into header and implementation

本文关键字:实现 方法 类库 分离      更新时间:2023-10-16

假设有一个名为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;}
}

命名空间中的所有声明将放在一起。因此,在命名空间内调试和跳转将很容易。

此外,大多数开源项目使用第二次实现