关于类相互调用的讨论
实现方式1:
A.h
#ifndef _A
#define _A
<strong> #include "B.h"//A的头文件导入了B的头文件</strong>
//extern class B;
class A
{
private:
int a;
B objectb; //A的头文件导入了B的头文件,在调用B的时候就可以不用指针
public:
A();
int geta();
void handle();
};
#endif _A
A.cpp
#include <iostream>
<strong> #include "A.h"</strong>
using namespace std;
A::A()
{
this->a= 100;
}
int A::geta()
{
return a;
}
void A::handle()
{
cout<< "in A , objectb.b="<<objectb.getb()<< endl;
}
B.h
#ifndef _B
#define _B
<strong> //#include "A.h"//B的头文件没有导入A的头文件,需要有三个地方需要注意!
extern class A; //注意1:需要用extern声明A</strong>
class B
{
private:
int b;
A* objecta; //注意2:调用A的时候需要用指针
public:
B();
int getb();
void handle();
};
#endif _B
B.cpp
#include <iostream>
<strong> #include "B.h"
#include "A.h"//注意3:在B.cpp里面导入A的头文件</strong>
using namespace std;
B::B()
{
this->b= 200;
}
int B::getb()
{
return b;
}
void B::handle()
{
objecta= new A();
cout<< "in B , objecta->a="<<objecta->geta()<< endl;
}
handle的多种形式,可以通过参数方式进行调用
形式一:
handle(A *a){【由于拷贝会导致更大的开销】
cout<< “in B , objecta->a=”<<objecta->geta()<< endl;
}
形式二:【更推荐,但可能会存在多线程调用导致的数据不一致问题】
handle(A &a){
cout<< “in B , objecta->a=”<<objecta->geta()<< endl;
}
第三种考虑在于静态方法的调用:
#include "Tesst.h"
#include "CShop.h"
void Tesst::show(CShop &cs) {
CShop::ShowPrice();
}
返回静态对象,每次调用时获取静态对象
static TEST* Get() {
static test e;
return &e;
}