【发布时间】:2013-05-22 22:45:18
【问题描述】:
#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;
但是,我不确定这种做法是否合法。
谢谢
【问题讨论】:
标签: c++