为什么我不能将指针的常量引用作为函数参数 为什么C++不编译以下内容?< /P> void func(const int *&pp) { //Do stuff } void functconst int*&pp { //做事 } int main { int-var=23; int*ptr_to_var=&var; 函数到变量; }

为什么我不能将指针的常量引用作为函数参数 为什么C++不编译以下内容?< /P> void func(const int *&pp) { //Do stuff } void functconst int*&pp { //做事 } int main { int-var=23; int*ptr_to_var=&var; 函数到变量; },c++,C++,为了澄清这一点,我想传递一个指针作为对函数的引用,但指针不应该在函数中改变,因此常量 我得到的警告是: error: invalid initialization of reference of type 'const int*&' from expression of type 'int*' error: invalid initialization of reference of type 'const int*&' from expression of type 'int

为了澄清这一点,我想传递一个指针作为对函数的引用,但指针不应该在函数中改变,因此常量

我得到的警告是:

error: invalid initialization of reference of type 'const int*&' from expression of type 'int*'
error: invalid initialization of reference of type 'const int*&' from expression of type 'int*'
我可以这样做:

void functint**pp { //做事 } 但这并没有给出我想要的确切行为,因为现在我可以实际更改指针指向的位置,也就是说,我错过了const关键字

如果你愿意:

void func(const int **pp) 
{ 
    //Do stuff
} 
void functconst int**pp { //做事 } 这也不会编译,而且我不确定如果它会编译,它是否真的会做我想要的事情

为什么C++不编译以下内容?< /P>
void func(const int *&pp) 
{ 
    //Do stuff
}
这是格式良好的,任何符合标准的编译器都会编译它

我得到的警告是:

error: invalid initialization of reference of type 'const int*&' from expression of type 'int*'
error: invalid initialization of reference of type 'const int*&' from expression of type 'int*'
错误消息不是很清楚,但我认为它试图说明您试图用右值初始化引用。对非常量左值的引用不能绑定到右值

如果你愿意:

void func(const int **pp) 
{ 
    //Do stuff
} 
这也不能编译

这也是格式良好的,符合标准的编译器必须接受它

您可以看到这两个示例都成功编译

为什么C++不编译以下内容?< /P>
void func(const int *&pp) 
{ 
    //Do stuff
}
这是格式良好的,任何符合标准的编译器都会编译它

我得到的警告是:

error: invalid initialization of reference of type 'const int*&' from expression of type 'int*'
error: invalid initialization of reference of type 'const int*&' from expression of type 'int*'
错误消息不是很清楚,但我认为它试图说明您试图用右值初始化引用。对非常量左值的引用不能绑定到右值

如果你愿意:

void func(const int **pp) 
{ 
    //Do stuff
} 
这也不能编译

这也是格式良好的,符合标准的编译器必须接受它


您可以看到这两个示例都成功编译。

func打算做什么?您需要展示如何调用函数。在任何情况下,执行func int*ptr时,请按值传递地址指针。func没有修改prt并影响调用方的风险。那么,作为常量引用传递指针需要什么呢?这样做并不会提高性能,而且会使函数原型比imo需要的更模糊。您的问题与您的代码不一致。您的代码应该是void funcint*const&pp或void funcint const*const&pp。顺便说一句,将常量引用传递给指针是没有意义的。如果您希望避免昂贵的副本,从而只传递通常作为指针实现的引用,而将指针作为常量引用传递则没有好处,那么可以这样做func打算做什么?您需要展示如何调用该函数。在任何情况下,执行func int*ptr时,请按值传递地址指针。func没有修改prt并影响调用方的风险。那么,作为常量引用传递指针需要什么呢?这样做并不会提高性能,而且会使函数原型比imo需要的更模糊。您的问题与您的代码不一致。您的代码应该是void funcint*const&pp或void funcint const*const&pp。顺便说一句,将常量引用传递给指针是没有意义的。如果希望避免昂贵的副本,从而只传递通常作为指针实现的引用,而将指针作为常量引用传递则没有好处,那么可以这样做