首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >避免在不同结构中声明相同的数据类型

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

Stack Overflow用户
提问于 2014-06-24 08:14:38
回答 2查看 66关注 0票数 0

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

示例

代码语言:javascript
复制
 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;

}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-06-24 08:17:44

那么,为什么不创建一个共同的结构呢?

代码语言:javascript
复制
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++,则可以从公共结构继承:

代码语言:javascript
复制
struct struct_3 : Common
{
     ... un common stuff
}

但是,在可能的情况下,与继承相比,更喜欢组合。

票数 4
EN

Stack Overflow用户

发布于 2014-06-24 08:28:58

您可以将所有这些结构放在一个头文件(xx.h).When中,您需要这些结构,您可以包括这些头文件,例如‘include“xx.h’‘。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24381539

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档