函数中的 c++ - "a reference .. can not be initialized with a value" 的错误

c++ in function- an error for "a reference .. can not be initialized with a value"

在花费大量时间挖掘相关 posts/online 资源后,我仍然对我的问题感到困惑。 我的示例代码 (test.cc) 是:


void testsub(const int* &xx );
int main ()
{
 int* xx;
 xx= new int [10];
 testsub(xx);
 }
 void testsub(const int* & xx){}

读取的编译错误信息(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"."

为什么?感谢您的帮助。 最良好的祝愿, 婷

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.
}

正如错误信息所说,参数类型不兼容;该函数需要一个指向 const int 的指针,而您提供一个指向 int.

的指针

如果您问为什么这是不兼容的:允许它会破坏常量正确性,如本例所示:

void testsub(const int* &xx ) {
    static const int x;
    xx = &x;
}

int* xx;
testsub(xx);  // Shouldn't be allowed, because...
*xx = 666;    // BOOM! modifying a constant object.

也许试试这个

void testsub(const int* xx );
int main ()
{
    int xx [10];
    testsub(xx);
}
void testsub(const int* xx){}

您不需要 &,因为您传递的是指针作为参数。

当你转发一个"C-Array"(你的int[10])时,你将在你的函数中有一个指向这个数组第一个元素的指针。

void testsub(const int* xx );
int main ()
{
 int* xx;
 xx= new int [10];
 testsub(xx);
 }
 void testsub(const int* xx){}

我想你对你的书感到困惑,因为他们总是写类似 "Call by reference" 的东西。这并不意味着通过 & 将参数作为引用传递。 通常将数组的大小也传递给函数是很有用的......所以它喜欢:

void testsub(const int* xx, size_t arraySize);
int main ()
{
 int* xx;
 xx= new int [10];
 testsub(xx, 10);
 }
 void testsub(const int* xx, size_t arraySize){}

现在您可以在函数中访问数组,如果您想使用索引访问数组,则可以检查索引。

void testsub(int* xx, size_t arraySize)
{
  for(size_t i=0; i<arraySize; ++i)
  //                    ^ this way you will never try to access
  //                      memory, which does not belong to the array
  //                      => no seg fault, or whatever happens
  {
    // do sth. with the array ... for example setting values to 0
    xx[i] = 0;
  }
}