Круговые зависимости переполнения стека

Я пытаюсь скомпилировать что-то вроде следующего:

хиджры

#include "B.h"class A {
B * b;
void oneMethod();
void otherMethod();
};

a.cpp

#include "A.h"void A::oneMethod() { b->otherMethod() }
void A::otherMethod() {}

B.h

#include "A.h"class B {
A * a;
void oneMethod();
void otherMethod();
};

B.cpp

#include "B.h"void B::oneMethod() { a->otherMethod() }
void B::otherMethod() {}

До сих пор у меня не было проблем с использованием предварительных объявлений, но я могу использовать это сейчас, потому что я не могу использовать atributtes или методы только для объявленных вперед классов.

Как я могу решить это?

2

Решение

Пока я правильно понимаю ваш вопрос, все, что вам нужно сделать, это:

хиджры

class B;// Forward declaration, the header only needs to know that B exists
class A {
B * b;
void oneMethod();
void otherMethod();
};

a.cpp

#include "A.h"#include "B.h"//Include in the .cpp since it is only compiled once, thus avoiding circular dependency
void A::oneMethod() { b->otherMethod() }
void A::otherMethod() {}

B.h

class A;// Forward declaration, the header only needs to know that A exists
class B {
A * a;
void oneMethod();
void otherMethod();
};

B.cpp

#include "B.h"#include "A.h"//Include in the .cpp since it is only compiled once, thus avoiding circular dependency
void B::oneMethod() { a->otherMethod() }
void B::otherMethod() {}
2

Другие решения

В C ++, в отличие от Java и C #, вы можете определить функцию-член (предоставляя ее тело) вне класса.

class A;
class B;

class A {
B * b;
void oneMethod();
void otherMethod() {}
};

class B {
A * a;
void oneMethod();
void otherMethod() {}
};

inline void A::oneMethod() { b->otherMethod(); }
inline void B::oneMethod() { a->otherMethod(); }
6

Вы должны отложить использование членов класса до тех пор, пока этот класс не будет определен. В вашем случае это означает перемещение некоторых тел функций-членов в конец файла:

class B;

class A {
B * b;
void oneMethod();
void otherMethod() {}
};

class B {
A * a;
void oneMethod() { a->otherMethod() }
void otherMethod() {}
};

inline void A::oneMethod() { b->otherMethod() }

Вот типичное решение в нескольких файлах:

хиджры

class B;
class A {
B * b;
void oneMethod();
void otherMethod();
};

B.h

class A;
class B {
A * a;
void oneMethod();
void otherMethod();
};

a.cpp

#include "A.h"#include "B.h"
void A::oneMethod() { b->otherMethod() }
void A::otherMethod() {}

B.cpp

#include "A.h"#include "B.h"
void B::oneMethod() { a->otherMethod() }
void B::otherMethod() {}

main.cpp

#include "A.h"int main () { A a; a.oneMethod(); }
1

Поместите реализацию ваших функций в файлы cpp, и тогда cpp может включать оба заголовка.

0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector