My initial suspicion was that there was a circular dependency in my code and went through Resolve header include circular dependencies. But this hasn't resolved my compilation errors. Here is the code with 3 classes - A, G & N.
//A.h
#ifndef A_H_
#define A_H_
class com::xxxx::test::G;
namespace com { namespace xxxx { namespace test {
class A {
public:
A();
~A();
void method1(void);
private:
G* g;
};
} } }
#endif /* A_H_ */
//A.cpp
#include "A.h"
#include "G.h"
namespace com { namespace xxxx { namespace test {
A::A() {
g = new com::xxxx::test::G();
}
A::~A() {
delete g;
}
void A::method1() {
g->method2(*this);
}
} } }
//G.h
#ifndef G_H_
#define G_H_
class com::xxxx::test::A;
namespace com { namespace xxxx { namespace test {
class G {
public:
void method2(const A&);
};
} } }
#endif /* G_H_ */
//G.cpp
#include "N.h"
namespace com { namespace xxxx { namespace test {
void G::method2(const A& a) {
N n(a, *this);
}
} } }
//N.h
#ifndef N_H_
#define N_H_
#include "A.h"
#include "G.h"
namespace com { namespace xxxx { namespace test {
class N {
public:
N(const A& obj1, const G& obj2) : a(obj1), g(obj2) {}
void method3(void);
private:
A a;
G g;
};
} } }
#endif /* N_H_ */
I am getting about 10 compilation errors in A.h and A.cpp I am listing the compilation errors below:
./src/A.h:11: error: 'com' has not been declared
../src/A.h:25: error: ISO C++ forbids declaration of 'G' with no type
../src/A.h:25: error: invalid use of '::'
../src/A.h:25: error: expected ';' before '*' token
../src/A.cpp: In constructor 'com::xxxx::test::A::A()':
../src/A.cpp:16: error: 'g' was not declared in this scope
../src/A.cpp: In destructor 'com::xxxx::test::A::~A()':
../src/A.cpp:20: error: 'g' was not declared in this scope
../src/A.cpp: In member function 'void com::xxxx::test::A::method1()':
../src/A.cpp:24: error: 'g' was not declared in this scope
What could be the mistake in the above code?
Thank you in advance,
Regards,
Raghava.
The forward declaration
class com::xxxx::test::G;
is illegal. Members of a namespace must be declared within it.
namespace com { namespace xxxx { namespace test {
class G;
Also, as Kenny says, namespaces aren't used like this in C++. Unless your project is distributed as a library or is of reasonably large size (dozens of files minimum), you probably don't need your own namespace.
When the compiler tries to compile a.cop, the first thing it encounters (included from a.h) is this:
class com::xxxx::test::G;
At this point there is nothing to tell the compiler what exactly com, xxxx and test are. Each of these can be either a namespace or a class. This also means that G is unclear, which leads to all other errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With