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


例子:

在头文件CTest.h中,前向声明了class CFoo;

在测试文件Console.cpp中只包含了头文件CTest.h;程序运行正确。
 

 
  
  1. //CFoo.h  
  2. class CFoo  
  3. {  
  4. public:  
  5.     CFoo(int nx, int ny);  
  6.  
  7.     int GetXvalue();  
  8.     int Getyvalue();  
  9.     void SetXvalue(int nx);  
  10.     void SetYvalue(int ny);  
  11.  
  12. private:  
  13.     int m_nx;  
  14.     int m_ny;  
  15. };  
 
  
  1. //CFoo.cpp  
  2. #include "Foo.h"  
  3.  
  4. CFoo::CFoo(int nx, int ny)  
  5. {  
  6.     m_nx = nx;  
  7.     m_ny = ny;  
  8. }  
  9.  
  10. int CFoo::GetXvalue()  
  11. {  
  12.     return m_nx;  
  13. }  
  14.       
  15. int CFoo::Getyvalue()  
  16. {  
  17.     return m_ny;  
  18. }  
  19.  
  20. void CFoo::SetXvalue(int nx)  
  21. {  
  22.     m_nx = nx;  
  23. }  
  24.       
  25. void CFoo::SetYvalue(int ny)  
  26. {  
  27.     m_ny = ny;  
 
  
  1. //CTest.h  
  2. class CFoo;//前向声明  
  3.  
  4. class CTest  
  5. {  
  6. public:  
  7.     CTest();
  8. ~CTest();
  9.     int GetSum();  
  10.     int GetMargin();  
  11.  
  12. private:  
  13.     CFoo*   m_pFoo;  
  14. }; 
 
  
  1. //CTest.cpp  
  2. #include "Test.h"  
  3. #include "Foo.h"  
  4.  
  5. CTest::CTest()  
  6. {  
  7.     m_pFoo = new CFoo(50,30);  
  8. }
  9.  
  10. CTest::~CTest()
  11. {
  12. delete m_pFoo;
  13. }  
  14.  
  15. int CTest::GetSum()  
  16. {  
  17.     int nx = m_pFoo->GetXvalue();  
  18.     int ny = m_pFoo->Getyvalue();  
  19.  
  20.     return nx + ny;  
  21. }  
  22.  
  23. int CTest::GetMargin()  
  24. {  
  25.     int nx = m_pFoo->GetXvalue();  
  26.     int ny = m_pFoo->Getyvalue();  
  27.  
  28.     return nx - ny;  
  29. }  
 
  
  1. //Console.cpp  
  2. #include <iostream>  
  3. using namespace std;  
  4. #include "Test.h"  
  5.  
  6. int main()  
  7. {  
  8.     CTest ok;  
  9.     cout<<"ok.GetSum = "<<ok.GetSum()<<endl;  
  10.     cout<<"ok.GetMargin = "<<ok.GetMargin()<<endl;  
  11.     getchar();  
  12.     return 0;  
  13. }  

输出结果:

ok.GetSum = 80

ok.GetMargin = 20