小编Fra*_*uss的帖子

从易失性结构中索引元素在 C++ 中不起作用

我有这个代码:

\n
typedef struct {\n    int test;\n} SensorData_t;\nvolatile SensorData_t sensorData[10];\n\nSensorData_t getNextSensorData(int i)\n{\n    SensorData_t data = sensorData[i];\n    return data;\n}\n\n\nint main(int argc, char** argv) {\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n

它可以使用 gcc 版本 8.3 进行编译,但不能使用 g++ 进行编译。错误信息:

\n
main.c: In function \xe2\x80\x98SensorData_t getNextSensorData(int)\xe2\x80\x99:\nmain.c:8:34: error: no matching function for call to \xe2\x80\x98SensorData_t(volatile SensorData_t&)\xe2\x80\x99\n  SensorData_t data = sensorData[i];\n                                  ^\nmain.c:3:3: note: candidate: \xe2\x80\x98constexpr SensorData_t::SensorData_t(const SensorData_t&)\xe2\x80\x99 <near match>\n } SensorData_t;\n   ^~~~~~~~~~~~\nmain.c:3:3: note:   conversion of argument 1 would be ill-formed:\nmain.c:8:34: error: binding reference of type \xe2\x80\x98const SensorData_t&\xe2\x80\x99 to \xe2\x80\x98volatile SensorData_t\xe2\x80\x99 discards …
Run Code Online (Sandbox Code Playgroud)

c++

18
推荐指数
2
解决办法
1332
查看次数

未初始化为0的对象数组

我正在尝试使用0初始化一个对象数组(像这样(一个更复杂的项目的简化代码)):

#include <iostream>

struct Vector {
    float s[4];
    Vector() {}
    static Vector zero() {
        Vector v;
        v.s[0] = 0;
        v.s[1] = 0;
        v.s[2] = 0;
        v.s[3] = 0;
        return v;
    }
};

struct Test {
    Vector v[4] = { Vector::zero() };
};


int main(int argc, char** argv)
{
    Test t;
    for (int i = 0; i < 4; i++) {
        printf("%f %f %f %f\n", t.v[i].s[0], t.v[i].s[1], t.v[i].s[2], t.v[i].s[3]);
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

此代码应打印全0,但有时会打印不同的值。看起来只有数组的第一个元素被初始化了。但是,如果我编写float x [4] = {0},则数组x的所有元素都将初始化为0。有什么区别?在C ++标准中我可以从何处了解到此行为?

c++ language-lawyer

1
推荐指数
1
解决办法
102
查看次数

标签 统计

c++ ×2

language-lawyer ×1