如何将常量值设置为struct c ++

问题描述 投票:0回答:1

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

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

谢谢...

c++ pointers struct const constants
1个回答
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.