C++类的互相调用多种实现形式

66 篇文章 0 订阅

关于类相互调用的讨论

实现方式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;
            }

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值