关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。
想改进这个问题?将问题更新为 on-topic对于堆栈溢出。
8年前关闭。
Improve this question
这是代码:
#include <iostream>
using namespace std;
void mysize(int &size, int size2);
int main()
{
int *p;
int val;
p = &val;
cout << p;
mysize(&val, 20); // Error is pointed here!
}
void mysize(int &size, int size2)
{
cout << sizeof(size);
size2 = size2 + 6000;
cout << size2;
}
这是 GCC 的错误输出:
In function 'int main()': Line 10: error: invalid initialization of non-const reference of type 'int&' from a temporary of type 'int*' compilation terminated due to -Wfatal-errors.
这意味着什么?我不明白错误信息......非常数的无效初始化?我用两个参数声明了上面的原型(prototype)函数,一个是整数的引用,一个是整数值本身。我传递了 int 的引用(参见第 10 行),但这个错误一直在向我抛出。另外,它是如何“临时指针”的?
问题是什么?
最佳答案
val
是 int
, &val
是 val
的地址,它是指向 int
的指针.您的函数需要引用。你需要这样称呼它
mysize(val, 20);
并将签名更改为
void mysize(const int &size, int size2);
或者,甚至更好,
void mysize(int size, int size2);
因为你没有修改
size
.
关于c++ - 引用将参数传递给函数时出现奇怪的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19694463/