简体   繁体   English

C ++中的独立函数/数据

[英]Standalone functions/data in C++

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; 所以,假设我有一个带有命名空间的头文件,其中包含一些类C1和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. 现在假设在实现(CPP)中,我已经定义了C1,C2的所有成员函数,然后假设我有一些我希望C1和C2共享的常见数据,比如枚举和字符串数组,但我不知道我们一定希望他们成为任何一个班级的一部分。 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? 也许OOP的一个特定功能可能更适合这种事情?

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. 再次提前感谢任何想法/更正。

If C1 and C2 share some implementation details which should be kept local to the translation unit, that's fine. 如果C1和C2共享一些应该保留在翻译单元本地的实现细节,那很好。

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). 最好将它们放在cpp文件中的匿名命名空间中,这样以后就不存在链接器符号冲突的风险(即,如果库客户端轻率地向命名空间添加了某些东西并意外地重用了一个“私有”名称) 。

The cpp file might look like: cpp文件可能如下所示:

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(...) {
       ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM