将其投射到无效*&
Cast this to void*&
本文关键字:无效 更新时间:2023-10-16
我有一个接受void*&
作为参数的方法,我想将this
作为参数传递。
示例:
struct A
{
void foo()
{
bar((void*&)this);
}
private:
void bar(void*& p) {}
};
我有以下编译器错误:
cast_this.cpp: In member function 'void A::foo()':
cast_this.cpp:5:14: error: invalid cast of an rvalue expression of type 'A*' to type 'void*&'
bar((void*&)this);
^
有什么方法可以投射this
指针吗?
编辑:尝试bar((void* const &)this);
给出:
cast_this.cpp: In member function 'void A::foo()':
cast_this.cpp:5:25: error: binding 'void* const' to reference of type 'void*&' discards qualifiers
bar((void* const &)this);
^
cast_this.cpp:8:10: note: initializing argument 1 of 'void A::bar(void*&)'
void bar(void*& p) {}
^
this
是一个prvalue,它不能绑定到非常量左值引用。还有一个关于类型的问题,但值类别是一个亮点,所以我们不需要深入讨论。
你必须写这样的东西:
void *ptr = this;
bar(ptr);
函数签名void *&
表明函数可能会更改其参数。对象的地址不能更改,因此这表明函数没有按照您的想法执行,或者您对函数的效果有一些误解。
正如您的问题评论中所建议的,您可以使用const
限定(因为this
实际上是const
),但演员阵容和参数都需要它:
bar((void* const &)this);
void bar(void* const & p) {}
(事实上,根据下面的评论,一旦您更改了函数签名,您就不需要强制转换了)。这导致临时用this
的值初始化,并绑定到bar
的p
参数(感谢M.M.的解释)。
当然,如果你可以用这种方式更改bar
的签名,那么你也可以让它接受一个普通的void *
:
bar(this);
void bar(void* p) {}
或者,将指针值保存到另一个变量:
void * t = this;
bar(t);
注意,bar
的当前签名意味着它可能会在返回之前更改t
的值。
相关文章:
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 无法访问嵌套类.类的使用无效
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 如何解决错误:SCIP C++中的 SCIP 阶段无效 <10>
- 在没有参数列表的情况下使用模板名称"Event"无效,模板问题
- FFMPEG配置文件级别id大小无效
- 错误:从"int"到枚举c++的转换无效
- 如何修复此错误:className::className的无效使用
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- C++-模板嵌套类的引用初始化无效
- 错误:无效的预处理指令 #i 的意思是 #if?
- 多维数组 C++ 中数组下标的类型"int[int]"无效
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- 从 'int' 到 'int*' CPP 的转换无效
- 如何接受 [ENTER] 键作为无效输入并发送错误消息
- 由于无效的 ValidateRgn() 子窗口不会收到WM_PAINT消息
- C++ PTHREADS - 无效转换无效*(*)()到无效*(*)(无效*)
- 声明为无效的变量或字段'...' Ardunio 编译器上的错误
- 数组下标的类型"float*[float]"无效
- 修改 std::vector 会使迭代器无效吗?