I'm having a problem with this function. The function is supposed to return a type of StoredData
.
This is my struct:
struct StoredData
{
void* data;
int size;
int type;
int compareValue;
StoredData():
size(0),
type(0),
compareValue(0){}
};
And this is my function:
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;
}
Unfortunately, I'm having a problem with the line within the case statements with
*data = (bool)input2;
The error that I'm getting is that it must be a pointer to a complete object type. I need the void
variable to recognize the data, and I'm getting no luck. Anybody know a workaround?
I'm getting 2 error messages for each. The first is,
illegal indirection
And the second ones are,
error C2440: '=' : cannot convert from 'int' to 'void *'
error C2440: '=' : cannot convert from 'bool' to 'void *'
You can't dereference a void pointer. You will have to cast it to a pointer type you can dereference:
*(bool *) data = (bool) input2;
You are attempting to dereference a void pointer and set its value:
*data = (bool)input2;
This is meaningless to the compiler. What type will the result of *data
be?
You need to cast the void*
to something meaningful first:
*(bool*)data = (bool)input2;
Alternatively, you could initialize your dynamic variables with the correct values when you create them:
data = new int(input2);
...
data = new bool(input2);
Which wouldn't require you to cast anything.
void是不完整的类型。您不能创建不完整类型的对象。
You can't dereference a plain void*
, as it could point to basically anything. You aither have to make it point to something other (assigning to another pointer):
bool* bool_pointer = new bool;
*bool_pointer = static_cast<bool>(input2);
data = bool_pointer;
Or use typecasting:
*reinterpret_cast<bool*>(data) = static_cast<bool>(input2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.