在源文件中创建具有结构成员的结构

Creating a struct with struct members in a source file

我是制作自定义库的新手,正在尝试创建一个包含结构数据类型的库,该结构数据类型具有一些结构成员。我希望 children 仅在内部使用,但 parent 结构及其所有组件对用户来说是 public。我写的代码看起来像这样:

#ifndef MYHEADER_H
#define MYHEADER_H
private:
struct child1{
  int thing1;
  int thing2;
};
struct child2{
  char letter;
  int thing3;
};
public:
struct parent{
  int val;
  struct child1 name1;
  struct child2 name2;
};
#endif

所以我的问题是,我的 .cpp header 源文件应该是什么样子来创建这个,我的 .h header 是否正确?提前致谢

好的,我们走吧...

让我们首先区分声明和定义。当您说 int x; 时,您是在告诉您的计算机存在一个名为 x 的变量,并且它是一个整数。另一方面,当您说 x = 5; 时,您将 x 定义为数字 5.

函数、方法、类 和结构也会发生同样的情况。如下:

函数声明:

int foo(int, char);

函数定义:

int foo (int a, char c) { ... do something ... }

最后构造:

结构声明:

struct parent;

结构定义:

struct parent {
    int thing1, thing2;
    struct child1 c;
};

好吧,现在记住这是你的主程序将包含的 .h,然后将 .h 放入主程序将使用的

#ifndef HEADER_H
#define HEADER_H
struct child1;
struct child2;
struct parent {
    struct child1 c1;
    struct child2 c2;
};
void process_something_internal(struct parent);
#endif

并且在您的 .cpp 中您可以:

#include "header.h"
#ifdef HEADER_H
struct child1 {
    int t1, t2;
};
struct child2 {
    int t1, t2;
};
void process_something_internal(struct parent p) {
    int = p.child1.t1; // here you can access
    ...
}
#endif

在 CPP 中声明您的 child 结构并将它们按值存储到您的 parent 结构中是不可能的。为了给 parent 结构一个正确的二进制表示,需要知道成员占用多少字节。这只有在 child 结构可见时才有可能。

因为这是 C++,我将采用我们习惯的语法,所以我只是使用 parent p.

而不是 struct parent p

您有 2 个选项:第一个将内部结构的内部设为私有:

#ifndef HEADER_H
#define HEADER_H
#include <memory>
struct child1;
struct child2;
struct parent {
    std::unique_ptr<child1> c1;
    std::unique_ptr<child2> c2;
    ~parent();
};
#endif

代码位于 Compiler Explorer

如您所见,我们转发声明了 2 个 child 结构并将一些 unique_ptr 放入 parent 结构中。这确保了封装。我还为 parent 结构添加了一个析构函数,因为你的编译器应该能够在销毁 parent 结构时调用 child 结构的析构函数。

备选方案2更容易使用:

#ifndef MYHEADER_H
#define MYHEADER_H

struct parent {
 private:
  struct child1 {
    int thing1;
    int thing2;
  };
  struct child2 {
    char letter;
    int thing3;
  };

 public:
  int val;
  child1 name1;
  child2 name2;
};

#endif

代码位于Compiler Explorer

在这种技术中,一切都在同一个头文件中定义。它被简单地标记为私有,因此除非通过 parent 结构的函数才能访问它。不需要内存分配,因为我们现在知道 child 结构的确切大小。

根据我的经验,我建议将 parent 的所有 struct/class 成员设为私有。对于 children,无论如何都不应该在此 struct/class 之外访问它。这将使您的代码更易于维护。