【问题标题】:Initialize POD struct初始化 POD 结构
【发布时间】: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++


【解决方案1】:

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

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

ModifyPod() 函数中等效且更简单。

【讨论】:

  • 你也可以按照POD pod = {1, 'A', true, 3.14};的方式做一些事情
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-16
  • 1970-01-01
相关资源
最近更新 更多