前向声明和其引起的错误提示

    技术2026-06-09  3

    1. 什么是前向声明?

     

    前向声明就是:

     可以声明一个类而不定义它  class Screen;//declaration of the Screen class  这个声明,有时候被称为前向声明(forward declaration),在程序中引入了类类型的Screen.在声明之后,定义之前,类Screen是一个不完全类型(incompete type),即已知Screen是一个类型,但不知道包含哪些成员.    不完全类型只能以有限方式使用,不能定义该类型的对象,不完全类型只能用于定义指向该类型的指针及引用,或者用于声明(而不是定义)使用该类型作为形参类型或返回类型的函数.

     

    2. 为什么需要前向声明?

     

     

    C++ INCLUDE Rule : Use forward declaration when possible

    Suppose you want to define a new class B that uses objects of class A. B only uses references or pointers to A. Use forward declaration then : you don't need to include <A.h> . This will in turn speed a little bit the compilation. class A ; class B { private: A* fPtrA ; public: void mymethod(const& A) const ; } ; B derives from A or B explicitely (or implicitely) uses objects of class A. You then need to include <A.h> #include <A.h> class B : public A { } ; class C { private: A fA ; public: void mymethod(A par) ; } 一般出现的错误提示

             d:/mywork/ginfo/client/src/skcfw/mainfrm.h(830) : error C2146: syntax error : missing ';' before identifier 'm_PopUpBUMgr'

              归为一句话就是要“注意引用头文件的先后顺序”!或者就是本文提到的声明问题。从MS的MSDN中是可

              以推断出这个判断。

              http://msdn.microsoft.com/en-us/library/9xbcaa9t%28v=vs.80%29.aspx

    Spelling or capitalization error.

    Missing type specifier in the declaration of the identifier.(出现这个问题的原因,就是包含文件,循环包含,你找我,我找你...前向声明就是用来解决这个问题的。)

         4. 问题的解决办法。(环境:假设有A.h、A.cpp 、B.h 、B.cpp )

             A中需要B中的某个类对象...B中需要A中的某个方法(函数)

             示例如下:

             //A.h

             #include "B.h"

             ...

             ...

             ...

             B中某个类名      对象名字;//CCfwPopUPBUMgr           m_PopUpBUMgr;

     

           //B.h

           Class A中的某个类;//前向声明

           ...

           ...

           ...

           A中的某个类         *指针的名字;//CMainFrame                     *m_pMainFrame;

     

          //B.cpp

          #include "A.h"

          ...

     

     

     

     

    最新回复(0)