无法使用嵌套指向其他结构的初始化struct

时间:2011-09-30 19:49:41

标签: c++ struct initialization nested

我正在使用定义此结构的第三方库:

typedef struct
{
    unsigned short nbDetectors;
    //! structure of detector status
    struct DetectorStatus
    {
        unsigned int lastError;         //< last detector internal error
        float temperature;              //< detector temperature
        detector_state state;           //< detector state
        unsigned short mode;            //< detector mode

        struct EnergyStatus
        {
            power_source powerSource;           //< front-end power source
            frontend_position frontendPosition; //< front-end position relative to the docking station

            struct BatteryStatus
            {
                bool present;                   //< battery present or not in the detector
                unsigned short charge;          //< charge level of the battery (in %)
                float voltageLevel;             //< battery voltage level
                float temperature;              //< temperature of the battery
                unsigned short chargeCycles;    //< number of charge/discharge cycles
                unsigned short accuracy;        //< Expected accuracy for charge level (in %)
                bool needCalibration;

            } batteryStatus;

        } * energyStatus;

        struct GridStatus
        {
            detector_grid grid;

        } * gridStatus;

    } * detectorStatus;

} HardwareStatus;

库使用此结构作为其回调之一传递的数据。所以它是填满它的库,我只是阅读它。到目前为止,非常好。

但是现在我正在为这个库处理的设备编写一个模拟器,所以现在我必须填写其中一个结构,我无法正确使用它。

我试过了:

HardwareStatus status;
status.detectorStatus->temperature = 20 + rand() % 10;
e.data = &status;
m_pContext->EventCallback( EVT_HARDWARE_STATUS, &e );

编译时,我得到了:

warning C4700: uninitialized local variable 'status' used

然后我意识到......结构中的指针指向垃圾,很好地捕获Visual Studio!那么我试着从声明最内层结构(BatteryStatus)的实例开始,但是这不会编译...因为它不是typedef(它表示没有定义BatteryStatus类型)?所以我很难过......我如何填充结构?

3 个答案:

答案 0 :(得分:3)

你可以重视它:

HardwareStatus status = {};

如果要实例化BatteryStatus,可以通过完全限定名称来实现:

HardwareStatus::DetectorStatus::EnergyStatus::BatteryStatus bs;

答案 1 :(得分:3)

如果你想把所有东西放在堆栈上,你应该这样做:

// Getting structs on the stack initialized to zero
HardwareStatus status = { 0 };
HardwareStatus::DetectorStatus detectorStatus = { 0 };
HardwareStatus::DetectorStatus::EnergyStatus energyStatus = { 0 };
HardwareStatus::DetectorStatus::GridStatus gridStatus = { 0 };

// "Linking" structs
detectorStatus.energyStatus = &energyStatus;
detectorStatus.gridStatus = &gridStatus;
status.detectorStatus = &detectorStatus;

// Now you can fill and use them
status.detectorStatus->temperature = 20 + 3 % 10;
//...

答案 2 :(得分:1)

你是否尝试将结构设置为0?