简体   繁体   中英

Parent class holds a static instance of child class C++

I am declaring two classes like the following, A is the parent class, B subclass A:

//a.h
#include "b.h"
//class B;     Adding this line doesn't work
class A{
    static B b;
}

//b.h
#include "a.h"
class B:public A{     // XCode error here: expected class name

}

However, XCode 6.1 don't let me compile and keeps saying "expected class name".

In fact, I am trying to implement a state machine mentioned in the book Game Programming Patterns http://gameprogrammingpatterns.com/state.html#static-states . In that book, the parent state class holds static instances of the child classes.

Below code would suffice for you :-

//b.h
#include "a.h"     <<<< This requires full definition for `A`.
class B : public A
{ 

}

//a.h         <<<<< No need to include any file.
class B;
class A{
    static B b;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM