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

时间:2019-11-03 01:34:40

标签: c++ struct libraries

我是制作自定义库的新手,正在尝试创建一个包含具有某些struct成员的struct数据类型的库。我希望子级仅在内部使用,但父级结构及其所有组件必须对用户公开。我编写的代码如下所示:

#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标头源文件应该如何创建它,而我的.h标头是否正确?提前打塔克人

2 个答案:

答案 0 :(得分:0)

将子结构声明为CPP并将其按值存储到父结构中是不可能的。为了给父结构提供正确的二进制表示,需要知道成员占用了多少字节。仅当子结构可见时才有可能。

因为这是C ++,所以我将采用我们惯用的语法,因此,我只使用struct parent p而不是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个子结构,并将一些unique_ptr放入父结构。这样可以确保封装。我确实也为父结构添加了析构函数,因为在销毁父结构时,编译器应该能够调用子结构的析构函数。

备用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处的代码

在此技术中,所有内容都在同一头文件中定义。它只是简单地标记为私有,因此除非它是由父结构的函数访问的,否则无法访问它。不需要内存分配,因为我们现在知道子结构的确切大小。

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

答案 1 :(得分:-1)

好吧,走吧...

我们首先将声明与定义区分开。当您说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
相关问题