【问题标题】:way to separate non-class library into header and implementation将非类库分离为头文件和实现的方法
【发布时间】:2018-07-03 04:05:33
【问题描述】:

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

【问题讨论】:

  • 第二个更好。因为它易于维护。
  • 太基于意见了,我想。也就是说,我同意@coder3101。

标签: c++ header namespaces implementation


【解决方案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 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;}
}

命名空间内的所有声明都将放在一起。所以命名空间内的调试和跳转会很容易。

大多数开源项目也使用第二个实现

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多