2014-02-20 48 views
0

嗨,我有以下幾點:使用indefined類型的

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

我確切地說,一切都寫在一個單一的文件。

你能幫我理解我做錯了什麼嗎?

感謝您的幫助

納撒尼爾

回答

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的完整定義。

總之:前置聲明不起作用。提供完整的類型。

+0

不,它不。這只是普通的C語言,你可以通過只提供前向聲明來調用函數......這對於編譯器來說已經足夠了,鏈接時需要定義 –

+0

不,它是C++,它是一個成員函數。 –

+0

是的大聲笑我知道我正在寫C++ ...我剛剛明白你的意思,我以爲你告訴你要提供函數定義,實際上你告訴了提供完整的類定義。所以我所知道的一天是沒有辦法向前宣佈一個成員函數! –