c++ - 嵌套结构初始化

标签 c++ c++11 struct compiler-errors initialization

所以我遇到了一个问题,我已经为此奋斗了几个小时。 SO 上有各种各样的问题提示同一个问题,但没有适合我的解决方案..

我有两个结构

// \brief The state of a single joint position. Default value of the speed is the maximum it wil allow.
struct JointPosition
{
    /// \brief The degree to set the joint to.
    double degree = 0;
    /// \brief The max degrees per second it will allow during the move.
    double maxDegreesPerSecond = 0;
};

/// \brief Struct containing all joint positions as degrees.
struct JointPositions
{
    JointPosition base;
    JointPosition shoulder;
    JointPosition elbow;
    JointPosition wrist;
    JointPosition gripper;
    JointPosition wristRotate;
};

我想像这样初始化它们:

static const JointPositions pos = {
    {0, 0},
    {0, 0},
    {0, 0},
    {0, 0},
    {0, 0},
    {0, 0}
};

return pos;

但是当我这样做时,我的编译器会报错如下:

RobotArm.cpp:59:2: error: could not convert ‘{0, 0}’ from ‘<brace-enclosed initializer list>’ to ‘JointPosition’

只要结构没有构造函数,Afaik 大括号初始化器就应该与结构一起工作。

我在 gcc 7.3 中使用 c++11。

感谢任何帮助。

这是演示该问题的在线链接:

https://onlinegdb.com/HkKzwoLhb

最佳答案

问题是您使用的 C++ 版本。

在这个 Live Demo ,我可以使用 GCC 7.2.0 和 C++11 重现您的问题。

切换到 C++14 会立即修复错误。

关于c++ - 嵌套结构初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46624086/

相关文章:

ios - 扩展结构不是 Swift 的成员

struct - 为什么生命周期强制转换适用于结构而不适用于特征?

C - 如何 malloc 包含字符串和数组的结构?

c++ - 为什么我可以阻止基元的隐式转换而不是用户定义的类型?

c++ - wchar_t 和 char16_t 在 Windows 上是一样的吗?

c++ - 如何传递带有泛型参数作为参数的 lambda 函数?

C++11:Variadic模板函数参数包扩展执行顺序

c++ - 在 Boost Phoenix 表达式中转换函数体

c++ - 在标准类型上使用原子操作

c++ - 仿函数和 initializer_list 的拷贝