gpt4 book ai didi

c++ - 修改调用另一个类函数的类中的变量

转载 作者:行者123 更新时间:2023-11-27 23:55:34 28 4
gpt4 key购买 nike

我有一个问题,我几乎可以肯定我可以通过重构我必须消除问题的代码找到一个解决方案,但我想知道是否有一种方法可以用我现在的方法实现相同的结果。

假设我们有 A 类:

class A
{
public:
int thing;
void dostuff();
std::list<B> mList;
}

void A::doStuff()
{
for(auto x : mList)
x.doMoreStuff();
}

然后是B类。

class B
{
void doMoreStuff();
}

是否有可能以任何方式使 B 的 doMoreStuff 更改类 A 的“int thing”变量而不将类 A 的实例传递给 B 或类似的复杂方法?

最佳答案

如果您只想更改某个实例的值,则必须引用。

你可以做的是使用 B 中方法的返回值

class A
{
int thing;
B b;
void dostuff() {
thing += b.doMoreStuff();
};
}

class B
{
int doMoreStuff() {
return 1;
};
}

或者您可以将 int thingvoid doMoreStuff() 设为 static 以便可以从类内存而不是实例内存访问它像这样:

class A
{
static int thing;

void dostuff() {
B.DoMoreStuff();
};
}


class B
{
static void doMoreStuff() {
A.thing += 2;
};
}

关于c++ - 修改调用另一个类函数的类中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42828397/

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