我忘了从函数中返回值但是当我在函数声明中返回引用时它工作了.为什么?

Abh*_*han 5 c++

#include <iostream>
#include<stdlib.h>
using namespace std;

class test{
    public:
    test(int a):i(a){
    }
    int display();
    private:
        int i;
};

int test::display(){
    i;
}
int main() {
    test obj(10);
    cout<<obj.display();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在上面的情况下,打印一些随机值.但是当我将函数声明更改为:

int& display();
Run Code Online (Sandbox Code Playgroud)

和定义为:

int& test::display(){
    i;
}
Run Code Online (Sandbox Code Playgroud)

它显示正确的值,即10我不知道为什么?

das*_*ght 7

这是未定义的行为,因此一切皆有可能 - 包括当您的代码按预期"工作"时的可能性.您的编译器应该对此发出警告 - 将此类警告视为错误并在测试代码之前修复所有报告的问题非常重要.

编译器使用堆栈或CPU寄存器从函数返回值.如果return缺少a,则不会在返回值的空间中放置任何数据.但是,您计划返回的数据可能已经位于寄存器中或堆栈中的正确位置,因此调用代码显示您期望的行为.但它仍未定义.