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);
}