i have two classes A and B
A.hpp
#include <vector>
#include <algorithm>
#include "B.hpp"
class A {
public:
void sortTrans() { std::sort(trans_.begin(), trans_.end(), sortStruct); }
unsigned int name() { return name_; }
private:
std::vector<B*> trans_;
unsigned int name_;
};
B.hpp:
class A;
class B {
A& source_;
A& dest_;
unsigned int choice_;
};
Now I want to sort trans_ by the values of choice and name, therefore i wrote
struct sort {
bool operator()(B* t1, B* t2) {
if (t1->choice < t2->choice)
return true;
if (t1->dest_.name() < t2->dest_.name())
return true;
return false;
}
} sortStruct;
But now I’m facing a problem to break the circular dependency. The definition of A is in A.hpp and the one of B in B.hpp. In B.hpp I use a forward decleration of A and A includes B.hpp. But where (or how) do i have to put the sortStruct, since it uses the definition of either, A and B. And I’m always getting the error
Wrong usage of forward declaration A
Thanks for help.
Both headers can use forward declation, since neither really (needs to) depend on the other.
A.hpp
B.hpp
A.cpp
Note I still haven’t shown how B::choice_ and B::dest_ are accessed, because this is a design decision and I don’t have enough information to make a good guess.
You can either expose them as public (in which case
Bis basically a struct), add accessor members toB, or forward-declareSortBin B.hpp as a friend.