为什么只有在打印到stdout的情况下,此函数才能在C ++中起作用?

时间:2019-05-10 14:09:36

标签: c++ reference printf cout dereference

我试图了解引用/指针/取消引用在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 ...

所以我的问题如下:

  1. 函数plusThree()为什么不起作用?是因为int&意味着它应该返回一个整数引用,但是return threeMore返回一个int?

  2. 如果plusThree()std::cout之一未注释,为什么函数printf现在可以工作?

谢谢!

1 个答案:

答案 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;
}