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

Modifying a variable in class that calls function of another class

本文关键字:类函数 变量 另一个 调用 修改      更新时间:2023-10-16

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

假设我们有类 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;
    };
}

是的,你可以简单地传递 A 的 int 事物的地址,例如:

B.doMoreThing(&myInt);

doMoreThing的定义是:doMoreThing(int * myInt),当修改函数内部int的值时,您应该这样做*myInt+=5 *对于访问变量很重要。

如果没有引用或指向事物的指针,您将无法写入事物。也就是说,反正事情是私人的,所以你需要一个二传手。或者,你可以让 B 成为 A 的朋友,或者给 B 一个指向事物成员的指针。