class foo; in header file

后端 未结 9 2004
执笔经年
执笔经年 2021-01-20 08:36

Is some one able to explain why header files have something like this?

class foo; // This here?
class bar
{
   bar();

};

Do you need an in

9条回答
  •  清歌不尽
    2021-01-20 08:53

    Try to think of writing this:

    file bar.h:

            #include "bar.h"
    
            class Foo
            {
            Bar* bar_ptr;
            }
    

    file foo.h:

            #include "foo.h"
    
            class Bar
            {
                Foo* foo_ptr;
            }
    

    This won't work, first due to infinite #include chain, then if you get rid of one of the includes, either Foo won't know what Bar is, or Bar won't know what Foo is.

    Try this instead:

            class Bar;
    
            class Foo
            {
            Bar* bar_ptr;
            };
    

    file foo.h:

            class Foo;
    
            class Bar
            {
                Foo* foo_ptr;
            };
    

提交回复
热议问题