在前向声明中使用未定义类型[重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

我有以下内容:

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)。

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

能帮我理解我做错了吗?

c++ forward-declaration
2个回答
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
}

0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.