2013-05-22 9 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라는 이름이 정확합니까? 먼저 struct (즉, pod)에 로컬 struct (즉, tmpPOD)의 값을 할당하여 구조체를 초기화합니다. 그런 다음 변수가 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

예, 합법입니다. I''ll는 당신이 동등한 간단하다 ModifyPod() 기능에

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

을 할 수있는 단지를 추가합니다.

+0

또한 할 수 있습니다. 'POD pod = {1, 'A', true, 3.14}의 행을 따라' –