我是制作自定义库的新手,正在尝试创建一个包含具有某些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标头是否正确?提前打捆
好,走吧...
让我们第一个将声明与定义区分开来。当您说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并将其按值存储到您的父结构中是不可能的。为了给父结构提供正确的二进制表示,需要知道成员占用了多少字节。仅当子结构可见时才有可能。
因为这是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
您可以看到,我们向前声明了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
在这种技术中,所有内容都在同一头文件中定义。它只是简单地标记为私有,因此除非它是由父结构的函数访问的,否则无法访问它。无需分配内存,因为我们现在知道子结构的确切大小。
根据我的经验,我建议将父级的所有结构/类成员设为私有。对于孩子,无论如何都不应在此struct / class之外访问它。这将使您的代码更易于维护。