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;
}

Question> I need to design a function that modify the pass-in variable pod. Is the above function named as ModifyPOD correct? First, I initialize the struct by assigning it(i.e. pod) with the value from a local struct(i.e. tmpPOD). Then, the variable is passed to Func. I use the local variable to initialize the pod so that I can avoid to do the following instead:

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

However, I am not sure whether this practice is legitimate or not.

Thank you

4

1 回答 1

0

是的,这是合法的。我只是补充说你可以做到

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

ModifyPod()等效且更简单的功能中。

于 2013-05-22T14:45:18.407 回答