[英]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.