2013-05-22 191 views
0
#include <iostream> 

using namespace std; 

struct POD 
{ 
    int i; 
    char c; 
    bool b; 
    double d; 
}; 

void Func(POD *p) { ... // change the field of POD }  

void ModifyPOD(POD &pod) 
{ 
    POD tmpPOD = {}; 
    pod = tmpPOD; // first initialize the pod 
    Func(&pod); // then call an API function that will modify the result of pod 
        // the document of the API says that the pass-in POD must be initialized first. 
} 

int main() 
{ 
    POD pod; 
    ModifyPOD(pod);  

    std::cout << "pod.i: " << pod.i; 
    std::cout << ", pod.c: " << pod.c; 
    std::cout << " , pod.b:" << pod.b; 
    std::cout << " , pod.d:" << pod.d << std::endl; 
} 

問題>我需要設計一個函數來修改傳入變量pod。上述名爲ModifyPOD的函數是否正確?首先,我通過用來自本地結構(即tmpPOD)的值分配它(即pod)來初始化結構。然後,該變量傳遞給Func。 我用的是局部變量初始化吊艙,使我能避免這樣做,而不是執行以下操作:初始化POD結構

pod.i = 0; 
pod.c = ' '; 
pod.b = false; 
pod.d = 0.0; 

但是,我不知道這種做法是否合法。

謝謝

+0

http://stackoverflow.com/questions/4932781/why-is-a-pod-in-a-struct-zero-initialized-by-an-implicit-constructor-when-creati – q0987

回答

0

是的,這是合法的。我只是補充說,你可以做

pod = POD(); 
Func(&pod); 

ModifyPod()函數,這是相當和簡單的。

+0

你也可以做點什麼沿着'POD pod = {1,'A',真,3.14}'的路線 –