c++classstatic

declare the definition of a class separating from its body


Following code is in the same header file

#include <iostream>
               
class B
{
public:
    void doSth()
    {  
        A::func(1);
    } 
};

class A
{
public:
    static void func(int a)
    {
        std::cout<<"a = "<< a <<std::endl;
    }
};

If class A is defined after class B like above, the compiler will complain about ‘func’ is not a member 'A'.

My question is, is there anyway to solve this issue without changing the order how class B and class A are defined? Like putting a declaration of class A somewhere above class B? Thanks.


Solution

  • If you want B::doSth() to be declared and defined completely inside of B's class declaration, then you must move the full declaration of A ahead of B, eg:

    #include <iostream>
                   
    class A
    {
    public:
        static void func(int a)
        {
            std::cout << "a = " << a << std::endl;
        }
    };  
    
    class B
    {
    public:
        void doSth()
        {  
            A::func(1);
        } 
    };
    

    Otherwise, if you don't need B::doSth() to be completely inside the B class declaration then you can separate its declaration and definition, and then move the definition after the declaration of the A class, eg:

    #include <iostream>
                   
    class B
    {
    public:
        void doSth();
    };
    
    class A
    {
    public:
        static void func(int a)
        {
            std::cout << "a = " << a << std::endl;
        }
    };
    
    inline void B::doSth()
    {  
        A::func(1);
    } 
    

    Preferably, method definitions that are not inside their class declaration should be implemented in separate .cpp files instead, eg:

    A.h

    #ifndef A_H
    #define A_H
    
    class A
    {
    public:
        static void func(int a);
    };
    
    #endif
    

    A.cpp

    #include <iostream>               
    #include "A.h"
    
    void A::func(int a)
    {
        std::cout << "a = " << a << std::endl;
    }
    

    B.h

    #ifndef B_H
    #define B_H
    
    class B
    {
    public:
        void doSth();
    };
    
    #endif
    

    B.cpp

    #include "B.h"
    #include "A.h"
                   
    void B::doSth()
    {  
        A::func(1);
    }