MST

星途 面试题库

面试题:C语言匿名联合体在内存管理中的应用

假设有一个场景,需要在不同时刻存储不同类型的数据(整型、长整型、双精度浮点型),但为了节省内存空间,希望使用匿名联合体来实现。请设计一个数据结构,并编写函数来实现数据的存储和读取,同时要考虑类型安全问题,避免数据读取错误。
21.8万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>
#include <type_traits>

// 定义一个枚举类型来表示存储的数据类型
enum class DataType {
    INT,
    LONG,
    DOUBLE
};

// 使用匿名联合体实现数据存储
union DataUnion {
    int intValue;
    long longValue;
    double doubleValue;
};

// 定义数据结构
struct DataStorage {
    DataType type;
    DataUnion data;

    // 存储整型数据的函数
    void store(int value) {
        type = DataType::INT;
        data.intValue = value;
    }

    // 存储长整型数据的函数
    void store(long value) {
        type = DataType::LONG;
        data.longValue = value;
    }

    // 存储双精度浮点型数据的函数
    void store(double value) {
        type = DataType::DOUBLE;
        data.doubleValue = value;
    }

    // 读取数据的函数,使用模板元编程确保类型安全
    template<typename T>
    T read() const {
        static_assert(std::is_same<T, int>::value ||
                      std::is_same<T, long>::value ||
                      std::is_same<T, double>::value,
                      "Unsupported data type for read");
        if (std::is_same<T, int>::value && type == DataType::INT) {
            return data.intValue;
        } else if (std::is_same<T, long>::value && type == DataType::LONG) {
            return data.longValue;
        } else if (std::is_same<T, double>::value && type == DataType::DOUBLE) {
            return data.doubleValue;
        }
        throw std::runtime_error("Type mismatch during read");
    }
};

int main() {
    DataStorage storage;

    storage.store(10);
    std::cout << "Stored int value: " << storage.read<int>() << std::endl;

    storage.store(1000000000000LL);
    std::cout << "Stored long value: " << storage.read<long>() << std::endl;

    storage.store(3.14159);
    std::cout << "Stored double value: " << storage.read<double>() << std::endl;

    return 0;
}
  1. 枚举类型 DataType:用于标识当前存储的数据类型。
  2. 匿名联合体 DataUnion:实际存储不同类型数据的地方。
  3. 结构体 DataStorage:包含数据类型标识和联合体成员。
  4. 存储函数 store:根据传入的数据类型存储相应的值,并设置类型标识。
  5. 读取函数 read:使用模板元编程确保读取的数据类型与存储的类型一致,避免类型错误。在 main 函数中演示了如何使用这些函数进行数据的存储和读取。