C++ Forward Declaration confusion

后端 未结 1 1210
长发绾君心
长发绾君心 2021-01-28 18:49

I\'m having some problems with forward declaration, well, I\'m confused about everything. I have 3 classes that depend on each other. For example:

  • ClassA depends o
1条回答
  •  闹比i
    闹比i (楼主)
    2021-01-28 19:18

    #include 
    using namespace std;
    class B;
    class C;
    
    class A{
    public:
        static B instanceOfB;
        static C instanceOfC;
        static void foo(){
            cout << "A static foo called"<< endl;
        }
    };
    
    
    
    class C{
       static A instanceOfA;
    };
    
    A C::instanceOfA = A();
    
    
    class B{
        A instanceOfA;
    };
    
    B A::instanceOfB = B();
    
    
    int main(){
        cout << "main run"<

    1st, it is a bad design when class depends on each other. 2nd, this kind of depends should doesn't mean you have to hold the object of the class, instead, if this dependent is complicated, you need to use a "pointer" to the object instead of holding the object. "Pointer to object" means compiler will not require the full prototype of that class.

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