繁体   English   中英

在C ++中迭代结构

[英]Iterating a struct in C++

我在迭代结构时遇到了一些麻烦。

可以根据编译器标志以不同方式定义结构。 我想将所有结构成员设置为0.我不知道有多少成员,但它们都保证是数字(int,long ...)

请参阅以下示例:

#ifdef FLAG1
    struct str{
        int i1;
        long l1;
        doulbe d1;
    };
#elsif defined (OPTION2)
    struct str{
        double d1
        long l1;
    };
#else
    struct str{
        int i1;
    };
#endif

我想我想做的一个很好的伪代码是:

void f (str * toZero)
{
    foreach member m in toZero
        m=0
}

有没有办法在c ++中轻松实现?

要在C ++中将任何PODO数据初始化为零,请使用= { 0 } 您不需要遍历每个成员。

StructFoo* instance = ...
*instance = { 0 };

为简单起见,您可能需要考虑以下列方式使用单个宏:

#define NUMBER_OF_MEMBERS 3

struct Str{
#if NUMBER_OF_MEMBERS > 0
    int i1;
#endif
#if NUMBER_OF_MEMBERS > 1
    double d1;
#endif
#if NUMBER_OF_MEMBERS > 2
    long l1;
#endif
};

void f (Str & str){

    #if NUMBER_OF_MEMBERS > 0
        str.i1 = 0;
    #endif
    #if NUMBER_OF_MEMBERS > 1
        str.d1 = 0;
    #endif
    #if NUMBER_OF_MEMBERS > 2
        str.l1 = 0;
    #endif

    return;
}

int main() {
    Str str;
    f(str);
}

其次,在创建类以启动零值后,您是否只调用f函数? 如果是这样,这更适合struct的构造函数方法。 在C ++ 11中,它可以像这样写得很干净:

#define NUMBER_OF_MEMBERS 3

struct Str{
#if NUMBER_OF_MEMBERS > 0
    int i1 = {0};
#endif
#if NUMBER_OF_MEMBERS > 1
    double d1 = {0};
#endif
#if NUMBER_OF_MEMBERS > 2
    long l1 = {0};
#endif
};

int main() {
    Str str;
    //no need to call function after construction
}

如果struct成员是由定义启用和禁用的,那么除了使用相同的定义来访问struct值之外,没有其他可能性。 但是,如果需要灵活性, struct可能不是最佳选择。

您可以使用C-way,因为它是一个pod:

memset(&str_instance, '\0', sizeof(str));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM