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

本文介绍了C++中的前向声明概念及其应用场景,解释了如何通过前向声明来避免不必要的头文件包含,从而提高编译速度。同时,还列举了一些常见的错误提示及解决方法。

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.
  1. 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 ;
    } ;
  2. 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) ;
    }
  3. 一般出现的错误提示

         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

  1. Spelling or capitalization error.

  2. 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"

      ...

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值