代码之家  ›  专栏  ›  技术社区  ›  HiroIshida

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

  •  0
  • HiroIshida  · 技术社区  · 8 年前

    假设有一个名为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;
      }
    }
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   coder3101    8 年前

    假设您的头中有多个名称空间或嵌套的名称空间,如下所示:

    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;}
    }
    

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

    同样,大多数开源项目使用第二个实现