Cycle [C ++] reference to the class filled pit

  Recently encountered a problem, cyclical references. That is, class A defines an object of class B, class B is also defined in the object's class A.

  Wrong configuration mode: direct new way, problems arise endless loop

//A.h
class B;
class A
{
public:
    A();
    ~A();
private:
    B* b;
};

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

A::A()
{
    b = new B();
}

A::~A()
{
    delete b;
    b = nullptr;
}

 

//B.h
class A;
class B
{
public:
    B();
    ~B();
private:
    A* a;
};

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

B::B()
{
    a = new A();
}

B::~B()
{
    delete a;
    a = nullptr;
}

  Really speaking, writing like this to see that there is a problem. But the trouble is that you do not know how to change it.

  Here it says, how to solve this problem elegantly.

  The correct manner of construction: Use a manner similar to the registered construction

//A.h
class B;
class A
{
public:
    A();
    ~A();
private:
    B * b;
}; 

//A.cpp
#include "a.h"
#include "b.h"

A::A()
{
    b = new B;
    B -> setA ( the this ); // draw key, in a manner similar to the configuration registered in the class B A 
}

A::~A()
{
    delete b;
    b = nullptr;
}
//B.h
class A;
class B
{
public:
    B (); // draw key is not required to achieve 
    ~ B ();
     void setA (A * X);
 Private :
    A * a;
};

//B.cpp
#include "b.h"
#include "a.h"

void B::setA(A * x) 
{ 
    a = x;
}

Guess you like

Origin www.cnblogs.com/LampsAsarum/p/12100816.html