gpt4 book ai didi

C++在类中设置引用变量然后更改

转载 作者:行者123 更新时间:2023-11-28 03:33:11 28 4
gpt4 key购买 nike

假设我有一个 Foo 类,它有一个 Bar 类型的引用变量和一个构造函数,如下所示:

Foo.h:

class Foo {
public:
Bar& m_b;

Foo(Bar& b);
}

Foo.cpp

Foo::Foo(Bar& b) : m_b(b) {
}

在单独的类(class)中我有:

// global 
Bar b;
Foo f(b);

int main() {
b.setData(); // actually set some values...
f.m_b.showData(); // will it show the change?
return 0;
}

调用setData()后,f中的引用变量是否也会有数据的变化?我正在尝试这个解决方法,因为我有一个类有一个引用变量(必须在初始化期间设置)但我需要它是全局可访问的(在实际设置 Bar 中的数据之前声明)。

最佳答案

是的。 f.mbb 都指向同一个对象。

关于C++在类中设置引用变量然后更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11962506/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com