C++中关于两个类互相引用的问题

C++中关于两个类互相引用的问题

现在写一个程序碰到两个类之间的相互引用问题,定义了类A类B,A中使用了B定义的函数,B中也使用了A定义的函数,查阅多方资料写了一个示例程序:

//main.cpp
#include "A.h"
#include "B.h"

A myA;
B myB;
void main()
{
    myA.setAB();
    myB.setBA();
}
//A.h
#ifndef A_H
#define A_H
#include "B.h"
#include <iostream>
using namespace std;
class A
{
public:
    A();
    ~A();
    int setA(int m, int n);
    void setAB();
    B b;
private:

};
#endif
//B.h
#ifndef B_H
#define B_H
#include <iostream>
using namespace std;
class A;
class B
{
public:
    B();
    ~B();
    void setBA();
    int setB(int m, int n);
    A* a;
private:

};
#endif
//A.cpp
#include "A.h"
A::A()
{}

A::~A()
{}

int A::setA(int m, int n)
{
    return (m + n);
}

void A::setAB()
{
    int t = b.setB(1, 2);
    cout << "setA=" << t << endl;
}
//B.cpp
#include "A.h"
#include "B.h"
B::B()
{}

B::~B()
{}

void B::setBA()
{
    int t = a->setA(2, 3);
    cout << "setB=" << t << endl;
}

int B::setB(int m, int n)
{
    return (m + n);
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值