将定义的宏字符串转换为void*
convert defined macro string to void*
我定义了一个宏,如下所示:
#define SOME_STRING "some_string"
,并且存在一个类型为void*
的字段。因此,为了将"some_string"
的地址分配给该字段,我这样做了:
boxFixtureDef.userData = static_cast<void*>(SOME_STRING);
MVS 2012没有报错,但Xcode和g++报告错误:invalid static_cast from type 'const char [12]' to type 'void*'
。怎么了?如何解决这个问题?
使用const_cast删除constness。Static_cast不能改变变量的常量。
#include <iostream>
#define MACRO_TEXT "macro-text"
int main()
{
void *ptr = const_cast<char*>(MACRO_TEXT);
std::cout << ptr << std::endl;
return 0;
}
(你不需要显式地将char*转换为void*。它将隐式地完成)
小心些而已。你不允许修改userData中的值,因为原始指针是const char[],在这种情况下,你只能从userData中读取值
这解决了,但我不知道这有多正确:
boxFixtureDef.userData = reinterpret_cast<void*>(const_cast<char*>(SOME_STRING);
static_cast
不能抛弃constness。为此,需要const_cast
:
static_cast<void*>("something"); // This doesn't compile
static_cast<const void*>("something"); // This does
const_cast<void *>(static_cast<const void*>("something")); // This does, too.
同样,指向void *
的指针的隐式转换不影响cv限定符:
void *something = "something"; // This doesn't compile
void *something2 = const_cast<char *>("something"); // This does; the char * from the cast is implicitly converted
void *something3 = const_cast<void *>(static_cast<const void*>("something")); // This does, too, but is more verbose.
但是,如果有人试图修改结果指针指向的内容,那就是未定义行为。因此,如果boxFixtureDef.userData
指向的内容可以修改,则不应该这样做。如果不是,为什么不把它改成const void *
呢?
只用(void *)(SOME_STRING)
。
相关文章:
- Boost buffer_cast 无法从 void* 转换为 PointerToPodType
- 将void*转换为某种类型的shared_ptr
- 如何将 void* 转换为函数指针?
- 对 C++ 中的特定标头使用 extern C 关键字是否允许从 void* 转换为 char*?
- 如何将 void 转换为 typedef void(..)(浮动)
- 无法将参数 1 从"int (__thiscall A::* *)(void)"转换为"int (__cdecl *)(void)"
- 从 'void *' 转换为 'const std::string *&' 必须具有所有中间指针 const 合格
- x = malloc(n * sizeof (int));无法将 void 转换为 int
- 错误:请求从“ void”转换为“ QString”的非量表类型
- 使用 LLVM 从 const void * 转换为模板类型时出现问题
- 如何修复错误:请求从"void"转换为非标量类型"std::vector<int>"
- void* 转换为基类并调用虚函数
- 将 void* 转换为 std::function<void()>
- 无法将参数 4 从 'void' 转换为'const char *'
- C++11 无法将 std::condition_variable::wait 从 'void' 转换为 'bool'
- 如何在 C++11 中将"const void*"转换为函数指针?
- 似乎无法在 c++ 中将 void* 转换为结构
- 将 void 转换为字节
- void * 转换为 int 语法的问题
- C++从类型“void*”转换为类型“double”无效