Casting void* in constructor and accessing value

时间:2016-10-15 17:20:42

标签: c++

The following code does not compile as it can not see a way to deference a void pointer despite the fact a cast is taking place in the constructor. Is there anyway to get this code to compile or turn off the type safety?

#include "stdafx.h"
#include <iostream>

using namespace std;

IntWrapper(int _value) : value{ nullptr }
{
    value = new int(_value);
    value = static_cast<int*>(value);
}

int main()
{
    IntWrapper* foo = new IntWrapper(10);
    cout << *foo->value;
    cin.get();
    return 0;
}

I should note that whilst this code is a console application it is intended as a test for code that is being written in Unreal Engine. It is for this reason that I cannot use class templates to achieve the required functionality.

2 个答案:

答案 0 :(得分:2)

new int returns a an int*. Casting an int* to int* is a no-op and accomplishes nothing. After you cast the result of new to itself, you store it in a void* variable, which implicitly casts it to void*.

When you access foo->value, the type is void* because that's the type you defined for value. Whatever you do in the constructor won't change that. If you want to cast the void pointer, here's where you do it. That is you can cast the foo->value to int* and then dereference that.

Of course it would be much easier to just have value be an int* in the first place.

答案 1 :(得分:0)

首先,如果您使用&#34; - &gt;&#34;你正在取消引用左边的术语。

在你的情况下* foo,但由于foo是一个IntWrapper *,那么* foo是一个IntWrapper。

所以语法是foo-&gt; value或(* foo).value。

在另一个答案中所说的一切都是真的,这个静态演员绝对没有。

因此正确的代码更像是这样:

else
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.accessoryView = nil;
    }

由于您正在创建一个int包装器,因此struct中的void *类型不是很有用。使它成为一个int *会给你更好的错误处理,并且不需要输出foo-&gt;值来打印它或以int形式访问它。