函数中的c ++ - "引用...的错误无法用值初始化"

Tin*_*Lei -2 c++ const reference

在花了一些时间挖掘相关帖子/在线资源后,我仍然对我的问题感到困惑.我的示例代码(test.cc)是:


void testsub(const int* &xx );
int main ()
{
 int* xx;
 xx= new int [10];
 testsub(xx);
 }
 void testsub(const int* & xx){}
Run Code Online (Sandbox Code Playgroud)

编译错误消息(pgcpp)读取

"test.cc", line 7: error: a reference of type "const int *&" (not const-qualified)
cannot be initialized with a value of type "int *"
  testsub(xx);
          ^
1 error detected in the compilation of "test.cc"."

为什么?非常感谢您的帮助.祝福,婷

R S*_*ahu 5

int*不能在参数类型所在的地方使用const int* &.

说你有:

const int a = 10;

void foo(const int* & ip)
{
   ip = &a;
}

int main()
{
   int* ip = NULL;
   foo(ip);
   *ip = 20;  // If this were allowed, you will be able to
              // indirectly modify the value of "a", which 
              // is not good.
}
Run Code Online (Sandbox Code Playgroud)