c++ - 引用将参数传递给函数时出现奇怪的编译错误

标签 c++ reference compiler-errors

关闭。这个问题不符合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 行),但这个错误一直在向我抛出。另外,它是如何“临时指针”的?

问题是什么?

最佳答案

valint , &valval 的地址,它是指向 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/

相关文章:

c++ - 如何将 C++ 关键字 "this"与成员函数 "operator="一起使用?

angular - ng2-material-select angular2中的错误加载

c++ - 如何遍历 QStack 对象的元素?

c++ - 输入操作数是否在 C++ 中返回 bool 值?

c - 编译器如何理解给定函数是按值传递还是按引用传递?

perl - 如何在 Perl 中使用代码引用作为回调?

c - 什么时候 const 被认为是真正的 const?

objective-c - Obj-C 中的乘法问题

c++ - 如何将用户输入的颜色传递给 textcolor()?

C++ 模板,在不初始化的情况下声明对象