Circular dependencies of declarations

前端 未结 6 1234
眼角桃花
眼角桃花 2021-01-19 05:02

I am trying to implement example of visitor pattern, but I have trouble with circular dependecies of declarations of classes. When I do forward declaration of class Visitor,

6条回答
  •  长情又很酷
    2021-01-19 05:49

    Alexey Malistov's answer does solve your problem. It just also exposes the next problem.

    The gcc compiler is complaining about the vtable (which is used for classes with virtual functions, amongst other things). The rules it uses are documented (see docs):

    If the class declares any non-inline, non-pure virtual functions, the first one is chosen as the "key method" for the class, and the vtable is only emitted in the translation unit where the key method is defined.

    Now, Alexey's version of your class defines the non-inline, non-pure virtual function accept. So, gcc defers instantiation of the Land vtable until it sees the definition of Land::accept. Add that, and see if it works. Or, as Nicholaz says, just make it a pure virtual.

    Well, I do not want to "solve" the problem. I want to understand what is wrong and why

    Get used to seperating declarations from definitions. Except for the special case of templates, C++ tends to work better this way.

提交回复
热议问题