Home > OS >  how to call another class's member function?
how to call another class's member function?

Time:12-11

I have two class, class A, Class B, in class B has a static function like below:

class A {
public:
    void method(){ B::method(); }

};

class B {
public:
    static int method() {
        cout << "method of b" << endl;
    
    }
};

int main()
{
    class A a;
    a.method();
}

this code build error, because in class A, B is not be declared, but I want class A be defined earlier than class B, how should i do? I was thought it may need forward declaration, but it seems not this reason...

CodePudding user response:

Take a look at the modified code. Inline comments explain the changes:

class A { 
public:
    // only declare the method
    void method();
    // Do NOT define it here:
    // { B::method(); }
};

class B { 
public:
    static int method() {
        std::cout << "method of b" << std::endl;
        return 0;
    }   
};

// and now, as B implementation is visible, you can use it.
// To do this, you can define the previously declared method:
void A::method() { B::method(); }

int main()
{
    class A a;
    a.method();
}

Hint: Please never use using namespace std

  • Related