C ++中的独立函数/数据 [英] Standalone functions/data in C++

查看:61
本文介绍了C ++中的独立函数/数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这一点,并且搜索还没有发现任何特别有用的东西.因此,假设我有一个带有名称空间的头文件,该名称空间包含一些类C1和C2;

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

现在假设在实现(CPP)中,我已经定义了C1,C2的所有成员函数,然后假设我具有一些我希望C1和C2共享的通用数据,例如一个枚举和一个字符串数组,但是我不一定要让他们成为这两个类别的一部分.那么执行以下操作是否合法(请注意:它可以构建并正常工作);如果我将此实现导出为客户端应用程序的库又如何?这仍然有效吗?出于某种我应该意识到的原因,这种设计是否会被皱眉?也许OOP的特定功能可能更适合这种情况?

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.

推荐答案

如果C1和C2共享一些实现细节,这些细节应该保留在翻译单元的本地,就可以了.

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

最好将它们放在cpp文件中的匿名名称空间中,因此以后没有链接器符号冲突的风险(即万一库客户机轻描淡写地将某些内容添加到名称空间中并意外地重用了其中的私人"名称, 名称).

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:

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

这篇关于C ++中的独立函数/数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆