如何在 C++ 中转换指针
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/461236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to cast a pointer in C++
提问by Hymanhab
void foo(void **Pointer);
int main ()
{
int *IntPtr;
foo(&((void*)IntPtr));
}
Why do I get an error?
为什么我会收到错误消息?
error: lvalue required as unary ‘&' operand
Thanks
谢谢
回答by Mehrdad Afshari
void foo(void **Pointer);
int main ()
{
int *IntPtr;
foo((void**)&IntPtr);
}
回答by workmad3
When you do
当你做
(void*)IntPtr
you create a temporary variable, which is only an rvalue, and so can't be dereferenced.
您创建了一个临时变量,它只是一个右值,因此不能取消引用。
What you need to do is:
你需要做的是:
int main()
{
int* IntPtr;
void* VoidPtr = (void*)IntPtr;
foo(&VoidPtr);
}
or equivalent
或同等学历
回答by Tobias W?rre
(void*) is not an lvalue, it is kind of a casting operator, you need to have the ampersand to the immediate left of the variable (lvalue). This should be right:
(void*) 不是左值,它是一种强制转换运算符,您需要在变量 (lvalue) 的紧邻左侧放置与号。这应该是正确的:
foo(((void**)&IntPtr));
回答by Igor Semenov
More C++ style:
更多 C++ 风格:
foo( reinterpret_cast< void** >( IntPtr ) );
But remember, according to Standard such a cast is implementation specific. Standard gives no guarantees about behavior of such cast.
但请记住,根据标准,这种类型转换是特定于实现的。标准不保证此类演员的行为。
回答by Johannes Schaub - litb
As others point out, you have the order of the cast and the &
wrong. But why do you use void**
at all? That means that you accept a pointer to a void pointer. But that's not at all what you want. Just make the parameter a void*
, and it will accept any pointer to some object:
正如其他人指出的那样,你有演员的顺序和&
错误的。但是你为什么要使用void**
呢?这意味着您接受一个指向 void 指针的指针。但这根本不是你想要的。只需将参数void*
设为a ,它就会接受指向某个对象的任何指针:
void foo(void*);
int main () {
int *IntPtr;
foo(&IntPtr);
assert(IntPtr == NULL);
}
That's what void*
is for. Later, cast it back using static_cast
. That's a quite restrictive cast, that doesn't allow dangerous variants, unlike the C style cast (type):
这void*
就是为了。稍后,使用static_cast
. 这是一个非常严格的强制转换,不允许危险的变体,与 C 风格的强制转换(type) 不同:
void foo(void* p) {
int** pint = static_cast<int**>(p);
*pint = NULL;
}
If the function takes pointers to void*
, then that function can't accept pointers to int*
. But if the function accepts either or, then the function should accept void*
, and you should cast to the proper type inside the function. Maybe paste what you really want to do, we can help you better then. C++ has some good tools available, including templates and overloading, both of which sound helpful in this case.
如果函数接受指向 的指针void*
,则该函数不能接受指向 的指针int*
。但是如果函数接受 or ,那么该函数应该接受void*
,并且您应该在函数内部强制转换为正确的类型。也许粘贴您真正想做的事情,然后我们可以更好地帮助您。C++ 有一些很好的工具可用,包括模板和重载,这两者在这种情况下听起来很有帮助。