calling a class method from another class

前端 未结 1 1795
时光说笑
时光说笑 2021-01-25 10:36

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:
         


        
1条回答
  •  别那么骄傲
    2021-01-25 10:46

    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;
        }
    };
    

    0 讨论(0)
提交回复
热议问题