class foo; in header file

后端 未结 9 2007
执笔经年
执笔经年 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:52

    This is called forward declaration. The body of the class foo would be defined at a later part of the file. Forward declaration is done to get around cyclic dependencies: The definition of class Bar requires class Foo and vice versa.

    class Bar
    {
       Foo * foo;
    };
    class Foo
    {
       Bar * bar;
    };
    

    As you can see, Bar has a reference to Foo and vice versa. If you try to compile this, the compiler will complaint saying that it doesn't know anything about Foo. The solution is to forward declare the class Foo above the Bar (just like you declare the prototype of a function above the main and define its body later).

    class Foo; //Tells the compiler that there is a class Foo coming down the line.
    class Bar
    {
       Foo * foo;
    };
    class Foo
    {
       Bar * bar;
    };
    

提交回复
热议问题