C++ 对类成员的引用,但不更改值

c++ reference to a class member but not changing value

提问人:Neil Chou 提问时间:1/24/2021 更新时间:1/24/2021 访问量:206

问:

请帮我查看以下代码。

我想知道为什么变量“b”不是修改后的值。

我不能使用引用来更改值?

谢谢!

#include <iostream>

using namespace std;

class Foo{
    public:
        int a = 1;
        int& check(){
            return a;
        };
};

int main()
{
    int b;
    Foo foo;
    
    b = foo.check();
    cout << b << endl;
    
    foo.check() = 2;
    cout << foo.a << endl;
    cout << b << endl;

    return 0;
}

输出为

1
2
1
C++ C++11 传递

评论

3赞 Igor Tandetnik 1/24/2021
foo.check()返回对 的引用,但随后赋值会复制它所引用的值。 没有神奇地与该任务联系在一起。这没有什么不同foo.abbfoo.aint x = 1; int y = x; x = 2; // y is still 1

答:

2赞 Michael Surette 1/24/2021 #1

正如 @Igor Tandetnik 所指出的,foo.check 返回一个引用,但 b 是一个 int,而不是对 int 的引用,因此它保留了原始值。

你想要的可以通过以下方式实现......

#include <iostream>

using namespace std;

class Foo
{
public:
    int a = 1;
    int &check()
    {
        return a;
    };
};

int main()
{
    Foo foo;
    int &b { foo.check() };

    cout << b << endl;

    foo.check() = 2;
    cout << foo.a << endl;
    cout << b << endl;

    return 0;
}

评论

0赞 Neil Chou 1/24/2021
明白了。感谢您的详细解释!