c++ - 在函数中使用 void。认不出来

标签 c++ function struct void

我在使用此功能时遇到问题。该函数应该返回一种类型的 StoredData

这是我的结构:

struct StoredData
{
    void* data;
    int size;
    int type;
    int compareValue;

    StoredData():

        size(0),
        type(0),
        compareValue(0){}
};

这是我的职能:

StoredData SDI::Array::create(int size, int type, int compareValue)
{
    StoredData temp;
    void* data;
    int input;
    int input2;
    std::cout<<"What type of data would you like to insert?"<<std::endl;
    std::cout<<"1 - Integer"<<std::endl;
    std::cout<<"2 - Boolean"<<std::endl;
    std::cin>>input;
    std::cout<<"What is the value?"<<std::endl;
    std::cin>>input2;
    switch (input)
    {
    case 1:
        size = sizeof(int);
        type = 0;
        data = new int;
        *data = (int)input2;
        break;
    case 2:
        size = sizeof(bool);
        type = 1;
        data = new bool;
        *data = (bool)input2;
        break;
    }
    temp.compareValue=input2;
    temp.data = data;
    temp.type = type;
    temp.size = size;
}

不幸的是,我在 case 语句中遇到了问题

*data = (bool)input2;

我得到的错误是它必须是一个指向完整对象类型的指针。我需要 void 变量来识别数据,但我运气不好。有人知道解决方法吗?

我收到了 2 条错误消息。第一个是,

illegal indirection

第二个是,

error C2440: '=' : cannot convert from 'int' to 'void *'

error C2440: '=' : cannot convert from 'bool' to 'void *'

最佳答案

您不能取消引用 void 指针。您必须将其转换为可以取消引用的指针类型:

*(bool *) data = (bool) input2;

关于c++ - 在函数中使用 void。认不出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21095194/

相关文章:

c++ - libcurl 写入数据到数组

c++ - 为类编写复制构造函数会在析构函数中删除对象时发生意外崩溃

c++ - 使用 CRTP 确定性地生成代码

javascript - 为什么 <br> 没有添加到错误消息中?

python - 在不停止另一个功能的情况下运行一个功能

c - 如何关联一组可变长度变量?

c - 在c中使用struct访问多个堆栈

c++ - 如何使用着色器制作复古/ NEON /发光效果?

function - Neovim 中的 ALE Fixer 配置

c - `struct point makepoint(int,int)`是什么意思?