C++两个类相互引用错误留影

java中类相互引用很方便,c++中有编译顺序的问题

c++声明作用,告诉编译器,我声明的东西你要是找不到,那就跳过去吧,等全编译完你就可以找到了。


C1.h

#pragma once
#include "C2.h"
//C1.h要包含C2.h,C2.h也要包含C1.h时,//要在类C2.h的定义前加上另一个类的声明class C1;,//否则编译时后编译的类找不到先编译的类。
class C1
{
	
public:
	C1();
	~C1();
	C2 *pc2;//㈡这里要是写C2 pc2的话,在C2.h中就不能再写C1 pc1,会形成重复创建,可以在C2.h中写C2 *pc2

	void showC1();
};


C1.cpp

#include "StdAfx.h"
#include "C1.h"
#include <iostream>
using namespace std;

C1::C1()
{
	pc2 = new C2(this);
}

C1::~C1()
{
}

void C1::showC1()
{
	cout<<"showC1"<<endl;
}


C2.h

#pragma once

class C1;//C1.h已经include C2.h,C2.h就不能再include C1.h,这里只声明class C1;
class C2
{
	C1 *cc1;
public:
	C2(C1 * p);
	~C2();
	void showC2();
};


C2.cpp

#include "StdAfx.h"
#include "C2.h"
#include "C1.h"//因为C2.h中没有include C1.h只对C1类做了声明,所以要使用C1 *p只能在C2.cpp中include C1.h
#include <iostream>
using namespace std;

C2::C2(C1* p)
{
	cc1 = p;
	
}

C2::~C2()
{
}

void C2::showC2()
{
	cc1->showC1();//如果C2.h和C2.cpp都没引用C1.h,这里会报错pointer to incomplete class is not allowed
	cout<<"showC2"<<endl;
}


posted @ 2014-01-13 16:06  00000000O  阅读(241)  评论(0编辑  收藏  举报