避免在不同的结构中声明相同的数据类型

avoid declaring same data types in different structures

本文关键字:声明 数据类型 结构      更新时间:2023-10-16

我在代码中声明了2 -3个结构体,所有这些结构体都有一些共同的数据类型。我们公司有严格的规定,不能重复代码。所以我想知道是否有任何方法可以在一些函数中声明这些常见的数据类型,并在我们声明结构时使用该函数。

例子
 struct_1
    {
    ... un common stuff
    // below are common declaration .. how would I declare below data type in some function and
// call it here to declare those data type
    unsigned char char_1;
    unsigned int int_1;
    std::vector< small_structure> small_struct;
    }
struct_2
{
... un common stuff
unsigned char char_1;
unsigned int int_1;
std::vector< small_structure> small_struct;
}
struct_3
{
... un common stuff
unsigned char char_1;
unsigned int int_1;
std::vector< small_structure> small_struct;
}

为什么不创建通用结构呢?

struct Common {
    unsigned char char_1;
    unsigned int int_1;
    std::vector< small_structure> small_struct;
}
struct struct_3
{
    ... un common stuff
    struct Common commonStuff;
}

或者如果你使用c++,你可以从common struct继承:

struct struct_3 : Common
{
     ... un common stuff
}

你可以把所有这些结构放在一个头文件(xx.h)中。当您需要这些结构时,您可以包含这些头文件,例如' include "xx.h" '