如何将常量设置为struct C ++

时间:2019-03-27 18:07:15

标签: c++ pointers struct const constants

我无法为结构内的常量赋值,请遵循以下代码:

#include <iostream>
#include <stdio.h>

typedef struct
{
  float a;
  float b;
  float c;
  float intensity;
} PointXYZI;

typedef struct structParent{
  int x;
  int y;
  const PointXYZI* xyzi;
} structParent;

int main()
{

  float o = 10.f, p = 5.0f, z = 96.0f;

  PointXYZI points = {o, p, z};

  const structParent *data = {0,0, &points};

  std::cout << " *-* " << data.xyzi->c << std::endl;
  std::cout << " *-* " << points.a << std::endl;


  return 0;
}

此代码出现以下错误:

错误:标量对象“ data”在初始化程序const structParent * data = {0,0,&points};

中需要一个元素

谢谢...

1 个答案:

答案 0 :(得分:0)

以下是@UnholySheep的答案的示例版本。

void someFunc(const structParent &x)
//                             ^^^^^^
{
  std::cout << " @_@ " << x.xyzi->c << std::endl;
}

int main()
{

  float o = 10.f, p = 5.0f, z = 96.0f;

  PointXYZI points = {o, p, z, 0};
  //                        ^^^^^
  const structParent data = {0,0, &points};
  //                ^^^
  std::cout << " *-* " << data.xyzi->c << std::endl;
  std::cout << " *-* " << points.a << std::endl;

  someFunc(data);
  //      ^^^^^^^
  return 0;
}