jeudi 5 mars 2015

How do I get over this forward declaration error?


I'm trying to do a barebones example of a class A that provides callback methods to a dependent class B by passing a reference to itself. The best I've produced is the following:


a.h



#ifndef A_H
#define A_H

#include "b.h"

namespace b {
class ClassB;
}

namespace a {

class ClassA {
public:
ClassA();
b::ClassB* m_b;
void callback(const std::string& msg);
};
}

#endif


a.cc



#include "a.h"

a::ClassA::ClassA() {
m_b = new b::ClassB(this);
}

void a::ClassA::callback(const std::string& msg) {
std::cout << msg << '\n';
}

int main(void)
{
a::ClassA* doit = new a::ClassA();
delete doit;
return 0;
}


b.h



#ifndef B_H
#define B_H

#include <iostream>
#include <string>

namespace a {
class ClassA;
}

namespace b {
class ClassB{
public:
ClassB(a::ClassA* a_inst);
};
}

#endif


b.cc



#include "b.h"

namespace b {

ClassB::ClassB(a::ClassA* a_inst) {
a_inst->callback("Call me maybe");
}
}


This is the closest I can get to a compilation, but I'm left with the following errors:



b.cc: In constructor 'b::ClassB::ClassB(a::ClassA*)':
b.cc:6:9: error: invalid use of incomplete type 'struct a::ClassA'
b.h:8:8: error: forward declaration of 'struct a::ClassA'


How can I fix this? And is there a better way to construct this relationship?




Aucun commentaire:

Enregistrer un commentaire