我试图了解引用/指针/取消引用在c ++中的工作方式。请参见下面的示例代码:
#include <iostream>
#include <cstdio>
int& plusThree(int num)
{
int threeMore = num + 3;
//std::cout << "threeMore is " << threeMore << "\n";
//printf("threeMore is %d", threeMore);
return threeMore;
}
int main()
{
int three = plusThree(0);
std::cout << "three is " << three << "\n";
return 0;
}
函数plusThree()
不起作用,如果运行代码,则不起作用。它将返回three is 0
。但是,如果您取消注释打印threeMore
的任何一行,则main
现在将打印three is 3
...
所以我的问题如下:
函数plusThree()
为什么不起作用?是因为int&
意味着它应该返回一个整数引用,但是return threeMore
返回一个int?
如果plusThree()
或std::cout
之一未注释,为什么函数printf
现在可以工作?
谢谢!
答案 0 :(得分:0)
如 @Renired Ninja 所述,从函数返回对局部变量的引用具有未定义的行为...
int threeMore;
应该在函数外部定义,或者必须通过值而不是引用返回。
您必须更改plusThree
的实现或int threeMore;
变量:
int threeMore;
按引用返回:
int threeMore = 0;
int& plusThree(int num)
{
threeMore = num + 3;
//std::cout << "threeMore is " << threeMore << "\n";
//printf("threeMore is %d", threeMore);
return threeMore;
}
按值返回:
int plusThree(int num)
{
int threeMore = num + 3;
//std::cout << "threeMore is " << threeMore << "\n";
//printf("threeMore is %d", threeMore);
return threeMore;
}