[英]What is the best way to define a struct which is only needed by a certain class?
Given the following simplified class which contains a vector of MyStruct
objects, where should I define MyStruct
assuming that it's only being used inside of Foo
and should not be seen or used from outside? 给定下面包含
MyStruct
对象向量的简化类,我应该在哪里定义MyStruct
假设它只在Foo
,不应该从外部看到或使用?
class Foo
{
std::vector<MyStruct> array;
};
Two possibilities I've come across are putting the definition of MyStruct
right inside of Foo
or using an anonymous namespace. 我遇到的两种可能性是将
MyStruct
的定义放在Foo
内部或使用匿名命名空间。
If array is in any way a public part of Foo
interface, declare MyStruct like this: 如果array以任何方式成为
Foo
接口的公共部分,则声明MyStruct如下:
class Foo
{
public:
struct MyStruct { /* stuff */ };
/* ... */
};
Otherwise: declare it in the private section of Foo
. 否则:在
Foo
的私有部分声明它。
In this case, you have to define it in Foo
, since it has to be completely defined before you use it to instantiate std::vector
. 在这种情况下,您必须在
Foo
定义它,因为在使用它来实例化std::vector
之前必须完全定义它。 Otherwise, it depends; 否则,取决于; I'd tend to define it in a private namespace: an unnamed namespace in the implementation file if all of the functions are in a single source file, otherwise in a private, implementation header file in a private namespace (eg
FooPrivate
) if they aren't. 我倾向于在私有命名空间中定义它:如果所有函数都在单个源文件中,则在实现文件中是未命名的命名空间,否则在私有命名空间中的私有实现头文件(例如
FooPrivate
)中如果它们不是“T。
If you do not want it to be used outside Foo, then the best way is to declare it in the private section of Foo
如果你不希望它在Foo之外使用,那么最好的方法是在
Foo
的私有部分声明它
class Foo
{
struct My_Struct;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.