C++ 为什么两个FUN都返回相同的结果?

C++ 为什么两个FUN都返回相同的结果?,c++,reference,C++,Reference,我有两个函数 struct a { public: int* b; int *& fun1() { return b; } int * fun2() { return b; } }; void main() { a* some = new a; some->b = new int(1); int* x1 = some->fun1(); int* x2

我有两个函数

struct a
{
public:
    int* b;

    int *& fun1()
    {
        return b;
    }

    int * fun2()
    {
        return b;
    }
};

void main()
{
    a* some = new a;
    some->b = new int(1);

    int* x1 = some->fun1();
    int* x2 = some->fun2();

    return;
}
为什么两者都返回相同的值?
为什么如果
some->b
nullptr
这两个
func
s将毫无例外地返回null?

第一个函数返回对
some
指向的对象的原始数据成员
b
的引用。因此,您可以使用此引用更改原始数据成员
b

但您不能使用第二个函数执行相同的操作,因为它返回原始数据成员
b
的值的副本

这是一个演示程序

#include <iostream>

struct a
{
public:
    int *b;

    int * & fun1()
    {
        return b;
    }

    int * fun2()
    {
        return b;
    }
};

int main()
{
    a *some = new a;
    some->b = new int(1);

    some->fun1() = new int( 2 );

    std::cout << *some->b << std::endl;

//  This statement will not compile.    
//  some->fun2() = new int( 3 );

    delete some->b;
    some->b = nullptr;

    delete some;

    return 0;
}

如果取消对已注释语句的注释,将出现编译器错误。

为什么它们不返回相同的结果?这两个函数都存储在
int*
中。它们不会返回相同的值。你的测试只是忽略了这一点。我不知道你为什么会想到这一点。@upiorek为什么会导致异常?它只返回指针的引用。在哪里可以看到异常?
main()
返回
int
。请更换任何书或教程告诉你它没有。
2