类的前向声明
class CFoo;//declaration of the CFoo class
可以声明一个类而不定义它
这个声明,有时候被称为前向声明(forward declaration),在程序中引入了类类型的CFoo.
在声明之后,定义之前,类CFoo是一个不完全类型(incompete type),即已知CFoo是一个类型,但不知道包含哪些成员.
不完全类型只能以有限方式使用,不能定义该类型的对象,不完全类型只能用于定义指向该类型的指针及引用,
或者用于声明(而不是定义)使用该类型作为形参类型或返回类型的函数.
例子:
在头文件CTest.h中,前向声明了class CFoo;
在测试文件Console.cpp中只包含了头文件CTest.h;程序运行正确。
- //CFoo.h
- class CFoo
- {
- public:
- CFoo(int nx, int ny);
- int GetXvalue();
- int Getyvalue();
- void SetXvalue(int nx);
- void SetYvalue(int ny);
- private:
- int m_nx;
- int m_ny;
- };
- //CFoo.cpp
- #include "Foo.h"
- CFoo::CFoo(int nx, int ny)
- {
- m_nx = nx;
- m_ny = ny;
- }
- int CFoo::GetXvalue()
- {
- return m_nx;
- }
- int CFoo::Getyvalue()
- {
- return m_ny;
- }
- void CFoo::SetXvalue(int nx)
- {
- m_nx = nx;
- }
- void CFoo::SetYvalue(int ny)
- {
- m_ny = ny;
- }
- //CTest.h
- class CFoo;//前向声明
- class CTest
- {
- public:
- CTest();
- ~CTest();
- int GetSum();
- int GetMargin();
- private:
- CFoo* m_pFoo;
- };
- //CTest.cpp
- #include "Test.h"
- #include "Foo.h"
- CTest::CTest()
- {
- m_pFoo = new CFoo(50,30);
- }
- CTest::~CTest()
- {
- delete m_pFoo;
- }
- int CTest::GetSum()
- {
- int nx = m_pFoo->GetXvalue();
- int ny = m_pFoo->Getyvalue();
- return nx + ny;
- }
- int CTest::GetMargin()
- {
- int nx = m_pFoo->GetXvalue();
- int ny = m_pFoo->Getyvalue();
- return nx - ny;
- }
- //Console.cpp
- #include <iostream>
- using namespace std;
- #include "Test.h"
- int main()
- {
- CTest ok;
- cout<<"ok.GetSum = "<<ok.GetSum()<<endl;
- cout<<"ok.GetMargin = "<<ok.GetMargin()<<endl;
- getchar();
- return 0;
- }
输出结果:
ok.GetSum = 80
ok.GetMargin = 20
转载于:https://blog.51cto.com/qsjming/511561