[英]C++: Convert/Cast void pointer to struct reference
我想將一個空指針投射到結構引用。
帶有結構的最小示例:
#include "Interface.h"
class Foo
{
public:
Foo()
: mAddress((uint32_t*)0x0803D000)
// Okay
, mStructPtr(*static_cast<const Struct*>(mAddress))
// Error: invalid static_cast from type 'const void*' to type 'const Struct&
, mStructRef1(static_cast<const Struct&>(mAddress))
// Error: 'const void*' is not a pointer-to-object type
, mStructRef2(static_cast<const Struct&>(*mAddress))
{
}
private:
const void * const mAddress;
Struct* mStructPtr;
Struct& mStructRef1;
Struct& mStructRef2;
};
使用引用(如何在構造函數中初始化)是否有意義/可能,還是必須使用指針?
我要在這里伸出脖子,說這是您要嘗試做的基本工作:
class Struct { int x;};
class Foo
{
Foo() :
s(*static_cast<Struct *>(reinterpret_cast<void*>(0x0803D000)))
{}
Struct & s;
};
(而且這不能跨平台移植-請參閱所有評論)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.