首页 > 解决方案 > 如何将常量中的值设置为 struct c++

问题描述

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

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

我收到以下代码错误:

错误:标量对象“数据”在初始化程序中需要一个元素 const structParent *data = {0,0, &points};

谢谢...

标签: c++pointersstructconstants

解决方案


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

推荐阅读