forward declaration with vector of class type - pointer to incomplete class type not allowed

纵然是瞬间 提交于 2019-11-27 09:16:44

You can't forward declare members.

Instead, bar.cpp should #include both foo.h and bar.h. Problem solved.

In general, if you use the sequence:

  • Forward declare all class types
  • Define all class types
  • Bodies of class members

everything will be fine.

You don't have to include foo.h or bar.h from each other unless you're accessing the internals of either class from the other header file. Declare the classes as needed in the header files, then include both header files from your source file.

foo.h

#include <vector>
class bar;
class foo {
    public:
         foo();
         ~foo();
         std::vector<bar*> getBarObjects();
    private:
         std::vector<bar*> barObjects;
};

bar.h

class foo;
class bar {
    public:
        bar(foo *currentFoo);
        ~bar();
        bool dosth();
    private:
        foo *thisFoo;
}

bar.cpp

#include "foo.h"
#include "bar.h"

bool bar(foo *currentFoo) {
    thisFoo = currentFoo;
}

bool bar::dosth() {
    thisFoo->getBarObjects();
}

You forgot to forward declare the vector in foo.h. You also return the vector by-value from getBarObjects which is possibly not what you want and the forward declaration of the member function is useless.

Also: Use header guards. Prefer the appropriate smart pointer for your situation (std::shared_ptr, unique_ptr) over raw pointers. Watch out for constness.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!