calling a class method from another class

喜你入骨 提交于 2019-12-02 07:52:16

问题


I want to change a variable member of class B, in a method member of class A. Example:

A.h:
class A
{
    //several other things
    void flagchange();
}
A.cpp:
void A::flagchange()
{
    if (human) Bobj.flag=1;
}

I know that I need an object of class B, to change a variable member of B, but objects of B are not reachable in A. Is it possible by a pointer??


回答1:


but objects of B are not reachable in A

If objects of class B are not reachable by class A there's no way you can modify them. Once you refactored your design, you should pass it as an argument to the function:

class A {
    //several other things
    void flagchange(B& obj) {
        if (human)
            obj.flag = 1;
    }
};

I want to be able to toggle the flag from a method of class A for every object of B

You should declare your flag public variable as static in B:

class B {
public:
    static int flag;
};

int B::flag = 0;

And then, from inside A:

class A {
    //several other things
    void flagchange() {
        if (human)
            B::flag = 1;
    }
};


来源:https://stackoverflow.com/questions/21200015/calling-a-class-method-from-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!