簡體   English   中英

如何將所有struct成員設置為相同的值?

[英]How to set all struct members to same value?

我有一個結構:

struct something {
    int a, b, c, d;
};

是否有一些簡單的方法可以將所有a,b,c,d設置為某個值,而無需單獨鍵入它們:

something var = {-1,-1,-1,-1};

還有太多重復(假設結構有30個成員...)

我聽說過“構造”或其他東西,但我想在代碼的不同部分將這些值設置為其他值。

這是我對這個問題的第二個答案。 第一個按照你的要求做了,但正如其他評論員指出的那樣,這不是正確的做事方式,如果你不小心的話可能讓你陷入困境。 相反,這里是如何為您的結構編寫一些有用的構造函數:

struct something {
    int a, b, c, d;

    // This constructor does no initialization.
    something() { }

    // This constructor initializes the four variables individually.
    something(int a, int b, int c, int d) 
        : a(a), b(b), c(c), d(d) { }

    // This constructor initializes all four variables to the same value
    something(int i) : a(i), b(i), c(i), d(i) { }

//  // More concise, but more haphazard way of setting all fields to i.
//  something(int i) {
//      // This assumes that a-d are all of the same type and all in order
//      std::fill(&a, &d+1, i);
//  }

};

// uninitialized struct
something var1;

// individually set the values
something var2(1, 2, 3, 4);

// set all values to -1
something var3(-1);

只需給struct一個構造函數:

struct something {
    int a, b, c, d;
    something() {
        a = b = c = d = -1;
    }
};

然后使用它:

int main() {
   something s;    // all members will  be set to -1
}

您還可以使用構造函數重置成員:

int main() {
   something s;    // all members will  be set to -1
   s.a = 42;   
   s = something();  // reset everything back to -1
}

您可以為結構定義方法。 那么為什么不呢:

struct something {
    int a, b, c, d;

    void set_values(int val) 
    { 
      a = b = c = d = val;
    }
};

something foo;

foo.set_values(-1);

它絕對值得一提的是@sbi在評論中提出的觀點:如果你的目的是初始化結構,那么你應該使用構造函數。 您應該避免允許結構/對象的用戶將其置於不可用/錯誤狀態。

在我收集的時候,你希望你的結構保持POD但仍然希望有一些“方便構造函數”。
在這種情況下添加構造函數不會起作用,因為你丟失了POD-ness,因此我使用了一個輔助函數:

something make_something() {
    something s = { -1, -1, -1, -1};
    return s;
}

如果要將其設置為不同的值,請讓該函數采用可能的可選參數:

something make_something(int i = 0) {
     something s = { i, i, i, i };
     return s;
} 

現在,您可以將定義和初始化簡化為一行:

something s = make_something(-1);

建立結構和數組的聯合。 並使用循環初始化數組。

union something {
    struct {
       int a,b,c,d;
    };
    int init[4];
};

   something truc;
   for (int i=0; i<4; i++) truc.init[i] = -1;

如果你有

struct
{int a,b,c.......;}foo;

我寫了那段代碼,似乎工作正常:

int* pfoo;
for (int i = 0; i < sizeof(foo); i++)
{
    pfoo = (int*)((int)(&foo) + i*sizeof(int));
    *pfoo = f(i/2); //set the values (here: the values of a random function f)
}

它直接從&foo開始寫入內存(結構中第一個變量的地址)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM