错误:不允许指向不完整类类型的指针.我该怎么做?

use*_*215 3 c++ pointers class function

所以我一直坚持从一个类到另一个类共享一个函数的问题,而我找到的每个解决方案都没有解决我的问题.这里有一个例子(我向你保证还有其他例子),[http://software.intel.com/en-us/articles/cdiag436]

Bar.h

#ifndef __Bar_h_
#define __Bar_h_
#include "BaseApplication.h"  
#include <Foo.h>  

class Foo;  
Foo *foo;  

class Bar : BaseApplication
{
   public:
Bar(void);
~Bar(void);
   protected:
virtual void barCreate(void);
};
#endif
Run Code Online (Sandbox Code Playgroud)

Bar.cpp

#include "Bar.h"
#include <Foo.h>
Bar::Bar(void){}
Bar::~Bar(void){}
void Bar::barCreate(void)
{
     if(foo->foobar()==true) //error: pointer to incomplete class type is not allowed
        {//stuff}
}
Run Code Online (Sandbox Code Playgroud)

foo.h中

#ifndef __foo_h_
#define __foo_h_
class Foo
{
public:
Foo(void);
~Foo(void);
bool foobar(void);
};
#endif
Run Code Online (Sandbox Code Playgroud)

Foo.cpp中

#include "Foo.h"
Foo::Foo(void){}
bool Foo::foobar(void){ return true; }
Run Code Online (Sandbox Code Playgroud)

如果我能得到一些指示或解释我哪里出错将会很棒.

Dav*_*eas 5

你误解了这个错误.它并没有抱怨指向一个不完整的类型,而是关于取消引用它.

if(foo->foobar()==true)
Run Code Online (Sandbox Code Playgroud)

此时类型foo是不完整类型,因此编译器无法检查它是否具有foobar成员函数(或成员函数).

基本上对于不完整的类型,您可以声明和定义指针或引用,声明接口(接受或返回类型的函数).但除此之外,您无法创建该类型的对象,或者使用指针/引用除了复制指针/引用之外的任何其他内容.

关于你做错了什么,你需要更详细地查看你的真实文件.要么你没有包含定义的标题Foo,要么你有多种Foo类型(不同的命名空间?一个定义类型,另一个具有前向声明)或你的包含保护是错误的,即使你包括标题,保护也会丢弃内容头.请注意,在包含定义的头之后,Foo您不需要(也不应该)提供该类型的前向声明,因为这很容易导致在不同上下文中的多个声明Foo.如果删除转发声明无法编译,请找出原因并解决问题.