Standalone functions/data in C++

2019-05-04 18:47发布

I am not certain about this and searching a bit hasn't turned up anything specifically useful. So, supposing I have a header file with a namespace that contains some classes C1 and C2;

namespace my_namesp {

class C1 {
public:
  blah1;
  ...
private:
  blah2;
...
};

class C2 {
public:
  junk1;
  ...
private:
  junk2;
  ...
};

} //-End namespace

Now supposing in the implementation (CPP), I have all the member functions of C1, C2 defined, then supposing I have some common data that I want C1 and C2 to share, say, an enum and a string array, but I don't necessarily want them to be a part of either class. Then is it legal to do the following (note: it builds and works fine); and how about if I am exporting this implementation as a library for a client application? Would this still work? Is this kind of a design frowned upon, for any reason that I should be aware of? Perhaps a specific feature of OOP might be better suited for this kind of thing?

namespace my_namesp {

enum some_list_num {
   list_member1,
   list_member2,
   ...,
   list_length
}

static const std::string string_list[] = {
   str1,
   str2,
   ...,
   strN 
}

return_type C1::some_func1(...) {
   ...
}

...

return_type C1::some_func1(...) {
   ...
}

} //-End my namespace

Thanks in advance again for any ideas/corrections.

标签: c++ oop
1条回答
Summer. ? 凉城
2楼-- · 2019-05-04 19:47

If C1 and C2 share some implementation details which should be kept local to the translation unit, that's fine.

It is better to put them in an anonymous namespace in the cpp file, so there is no risk of linker symbol clashes later (ie, in case a library client rashly adds something to your namespace and accidentally reuses one of your "private" names).

The cpp file might look like:

namespace { // private implementation details

    enum some_list_num {
       list_member1,
       list_member1,
       ...,
       list_length
    }

    static const std::string string_list[] = {
       str1,
       str2,
       ...,
       strN 
    }

}

namespace my_namesp { // define externally-visible functions etc.

    return_type C1::some_func1(...) {
       ...
    }

    return_type C1::some_func1(...) {
       ...
    }
}
查看更多
登录 后发表回答