在前向声明中使用未定义类型

时间:2014-02-20 11:11:46

标签: c++ forward-declaration

我有以下内容:

class A; // forward declaration of class A
void A::foo(int, int); // forward declaration of member function foo of A

class Functor
{
public:
    Functor(const A* in_a):m_a(in_a){}
    virtual ~Functor(){m_a= 0;};

    virtual void Do(int,int) = 0;

protected:
    const A* m_a;
};

class FunctorDerived: public Functor
{
    FunctorDerived(const A* in_a):Functor(in_a){}

    void Do(int in_source, int in_target)
    {
        m_a->foo(in_source, in_target);
    }
};


class A
{
    ....
    void foo(int, int);
    ....
}

编译时编译器告诉我:

error C2027: use of undefined type 'A'
see declaration of 'A'

似乎编译器无法识别A,虽然我转发声明它并且还声明了我需要使用的成员函数(A :: foo)。

我想澄清一切都写在一个文件中。

你能帮我理解我做错了吗?

2 个答案:

答案 0 :(得分:1)

A的定义移到最顶层。然后,如果您需要实现foo

class A
{
    void foo(int, int);
}

class Functor
{
public:
    Functor(const A* in_a):m_a(in_a){}
    virtual ~Functor(){m_a= 0;};

    virtual void Do(int,int) = 0;

protected:
    const A* m_a;
};

class FunctorDerived: public Functor
{
    FunctorDerived(const A* in_a):Functor(in_a){}

    void Do(int in_source, int in_target)
    {
        m_a->foo(in_source, in_target);
    }
};

void A::foo(int x, int y)
{
    //do smth
}

答案 1 :(得分:0)

m_a-> - 您正在取消引用A*。此时,编译器需要A的完整定义。

简而言之:前方声明不起作用。提供完整的类型。

相关问题