前言:
C++中类必须先定义,才能够实例化。
两个类需要相互引用形成一个“环形”引用时,无法先定义使用。这时候需要用到前向声明前向声明的类不能实例化。
//前向声明的类,不能实例化一个对象,可以声明指针或引用对象
/*
* DemoA.h
*
* Created on: Jul 15, 2014
* Author: zfs
*/
#ifndef DEMOA_H_
#define DEMOA_H_
#include "DemoB.h"
class DemoA {
public:
DemoA();
virtual ~DemoA();
DemoB demob_;
};
#endif /* DEMOA_H_ */
/*
* DemoA.cpp
*
* Created on: Jul 15, 2014
* Author: zfs
*/
#include "DemoA.h"
DemoA::DemoA() {
// TODO Auto-generated constructor stub
}
DemoA::~DemoA() {
// TODO Auto-generated destructor stub
}
/*
* DemoB.h
*
* Created on: Jul 15, 2014
* Author: zfs
*/
#ifndef DEMOB_H_
#define DEMOB_H_
//#include "DemoA.h"
class DemoA;
class DemoB {
public:
DemoB();
virtual ~DemoB();
/*void fun1(DemoA demo){ //error
}*/
void fun1(DemoA& demo){ //
}
void fun2(DemoA* demo){ //
}
DemoA* demoa_; //前向声明的类,不能实例化一个对象,可以声明指针或引用对象
};
#endif /* DEMOB_H_ */
/*
* DemoB.cpp
*
* Created on: Jul 15, 2014
* Author: zfs
*/
#include "DemoB.h"
DemoB::DemoB() {
// TODO Auto-generated constructor stub
}
DemoB::~DemoB() {
// TODO Auto-generated destructor stub
}