向前声明与类类型的向量 - 指向不完整的类类型的指针不允许 [英] forward declaration with vector of class type - pointer to incomplete class type not allowed

查看:128
本文介绍了向前声明与类类型的向量 - 指向不完整的类类型的指针不允许的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类,foo和bar。 foo包含bar并包含指向bar对象的指针的std :: vector。在运行时期间的某个点,bar必须访问这个指向其他bar对象的指针的向量。因此,foo包含一个名为getBarObjects()的方法,它返回指针数组。

I have two classes, foo and bar. foo includes bar and contains a std::vector of pointers to bar objects. at some point during runtime, bar has to access this vector of pointers to other bar objects. Therefor, foo contains a method named getBarObjects() that returns the array of pointers.

因此,我在bar中转发声明foo。我obvioulsy也必须转发声明我使用的方法 - foo :: getBarObjects()。因为这返回指针数组到bar,我陷入一个恶性循环。

Therefor, I forward declarate foo in bar. I obvioulsy also have to forward declarate the method I'm using - foo::getBarObjects(). As this returns the array of pointers to bar, I get into a vicious cycle.

我不能转发包含Bar,然后简单地向前包括getBarObjects() 不允许不完整的类型名称。

I cannot forward include Bar and then simply forward include getBarObjects(), as this results in "incomplete type name is not allowed".

foo.h:

#include "bar.h"
#include <vector>

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

bar.h:

class foo;
std::vector<bar*> foo::getBarObjects();        // error, doesn't know bar at this point

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

bar.cpp:

#include "bar.h"

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

bool bar::dosth() {
    thisFoo->getBarObjects();        // error, pointer to inomplete class type is not allowed
}

另一方面,我会有同样的问题在foo lateron。任何建议?

If I simply include the other way around, I'll have just the same problem in foo lateron. Any suggestions?

推荐答案

您不能转发声明成员。

bar.cpp 应该 #include 两者 foo.h bar.h

一般来说,如果您使用顺序:

In general, if you use the sequence:


  • 声明所有类类型

  • 定义所有类类型

  • 类成员的身体

一切都很好。

这篇关于向前声明与类类型的向量 - 指向不完整的类类型的指针不允许的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆