Cross Reference Solution

I have a problem with creating some form of hierarchy with different types of objects. I have a class that has a member of another class, for example:

class A
{
public:
    A(){}
    ~A(){}

    void addB(B* dep){
        child = dep;
        dep->addOwner(this);
    }
    void updateChild(){
        child->printOwner();
    }
    void print(){
        printf("Printing...");
    }
private:
    B* child;
};

And this is class B:

class B
{
public:
    void addOwner(A* owner){
        ownerObject = owner;
    }

    //ISNT WORKING
    void printOwner(){
        ownerObject->print();
    }

private:
    A* ownerObject;
};

Calling function "B" from class "A" works just fine, but when you try it on the contrary, a compiler error occurs because A is not defined in B. Actually this happens with the include and forward declarations, but I guess its cross-reference problem that the compiler can't decide.

Is there a chance to solve this problem or should I rethink my design?

+3
source share
4 answers

, , A , , A , , . (.. , ).

- print ; , , - , . , - printOwner B :

//B.hpp

class A; // forward declaration

class B
{
  public:
    void addOwner(A* owner);

    void printOwner() const; // I think this member function could be const

  private:
    A* ownerObject;
};

//B.cpp

#include "B.hpp"
#include "A.hpp" // here we "import" the definition of A

void B::addOwner(A * owner)
{
    ownerObject = owner;
}

void B::printOwner() const
{
    ownerObject->print(); //A is complete now, so we can use its member functions
}

A.

+8

, , cccular parent-child .

:

#include <cstdlib>
#include <cstdio>

class A
{
public:
    A(){}
    ~A(){}

    void addB(class B* dep);
    void updateChild();
    void print(){
        printf("Printing...");
    }
private:
    class B* child;
};

class B
{
public:
    void addOwner(A* owner){
        ownerObject = owner;
    }

    //ISNT WORKING
    void printOwner(){
        ownerObject->print();
    }

private:
    A* ownerObject;
};

void A::addB(class B* dep){
    child = dep;
    dep->addOwner(this);
}

void A::updateChild(){
    child->printOwner();
}



int main()
{
    return 0;
}
+2

You can use the forward declaration and define member functions outside the class, i.e.

// A.h
class B;
class A { public:
  void addB(B* dep);   // don't define addB here.
  ...
};

// B.h
class A;
class B { public:
  void addOwner(A* owner);  // don't define addOwner here.
  ...
};

// A.cpp
#include "A.h"
#include "B.h"
void A::addB(B* dep) { 
   ...
}

// B.cpp
// similar.
+2
source

You must move the implementation of B :: printOwner to a .cpp file.

0
source

Source: https://habr.com/ru/post/1765287/


All Articles