![](/img/trans.png)
[英]Why can't I reference a pointer to a function of an instantiated object?
[英]Why can't I give constant reference of a pointer as function argument
为什么 c++ 不能编译以下?
void func(const int *&pp)
{
//Do stuff
}
int main()
{
int var =23;
int* ptr_to_var = &var;
func(ptr_to_var);
}
为了澄清,我想传递一个指针作为对 function 的引用,但不应在 function 中更改指针,因此不应更改 const。
我得到的编译警告是:
error: invalid initialization of reference of type 'const int*&' from expression of type 'int*'
我可以做这样的事情:
void func(int **pp)
{
//Do stuff
}
但这并没有给我我想要的确切行为,因为现在我实际上可以更改指针指向的位置,即我错过了 const 关键字。
如果你会这样做:
void func(const int **pp)
{
//Do stuff
}
这也不能编译,我实际上不确定它是否会编译它实际上会做我想要的。
为什么 c++ 不能编译以下?
void func(const int *&pp) { //Do stuff }
这是格式良好的,任何符合标准的编译器都会编译它。
我得到的编译警告是:
error: invalid initialization of reference of type 'const int*&' from expression of type 'int*'
错误消息不是很清楚,但我认为它试图说您尝试使用右值初始化引用。 对非常量左值的引用不能绑定到右值。
如果你会这样做:
void func(const int **pp) { //Do stuff }
这也不编译
这也是格式良好的,符合标准的编译器必须接受它。
您可以在此处看到这两个示例均已成功编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.