简体   繁体   English

定义仅某个类所需的结构的最佳方法是什么?

[英]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.

相关问题 一个类定义它的向量需要什么? - What things are needed for a class to define a vector of it? 在类内部的结构中定义枚举 - define enum inside a struct which is inside a class 删除std:list中元素的最佳方法是什么 <User_Define> 满足某些条件? - What is the best way to remove elements in a std:list<User_Define> that satisfy certain conditions? 当一次只需要其中一种类型时,保持指向不同类型的指针的最佳方法是什么? - What is the best way to keep a pointer to different types when only one of them is needed at a time? 在函数中填充结构图的最佳方法是什么 - what is the best way of filling map of struct in a function 在名称空间中定义双常量的最佳方法是什么? - What is the best way to define a double constant in a namespace? C ++ - 最佳实践#define值只写一次? - C++ - best practice #define values which are written only once? 创建仅在预定义的试用期(评估期)内有效的程序的最佳方法是什么? - What is the Best way to create a program which works only in the predefined trial period(evaluation period)? 在 C++ 中初始化位域结构的最佳方法是什么? - What is the best way to initialize a bitfield struct in C++? 在 C++ 中定义类作用域常量的最佳方法 - Best way to define class-scoped constant in C++
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM