Cannot create an instance of a class from another

2019-09-20 01:23发布

Okay, so this is really werid. I've never encountered anything like this.

Part of my program (Fails to compile) contains three namespaces as following:

// namespaceA.h
namespace A {
enum Kind { jimmy, david };
}
// end of namespaceA.h

// namespaceB.h
#include "namespaceA.h"
namespace B {
class Tree {
    public:
    Tree *prev;
    Tree *next;
    Tree *down;
    A::Kind kind;

    Tree();
    ~Tree();
};
}
// end of namespaceB.h
// Implementation details of the class are placed in namespaceB.cc
// Constructor / Desctructor defined in the namespaceB.cc file!
// Something like this,
#include "namespaceB.h"
namespace B {
inline Tree::Tree() { ... }
inline Tree::~Tree() { ... }
}

// namespaceC.cc
#include "namespace.B"
namespace C {
void run() {
    B::Tree *tree;    // FINE
    B::Tree tree;     // Fail to compile!?
}
}
// end of namespaceC.cc

Now, g++ went along just fine but the linker ld complains:

 "namespaceC.cc: undefined reference to `B::Tree::Tree()'
 "namespaceC.cc: undefined reference to `B::Tree::~Tree()'

I have never ever encountered anything like this before... This just seems really weird, I don't even know any words/terms to describe this problem.

I would much appreciate any help.

Thanks,

8条回答
Emotional °昔
2楼-- · 2019-09-20 02:01

That's not a namespace problem, neither a compiler error. The compiler is happy, but linker fails to find the definition of B::Tree::Tree(). You need to supply the source file for implementation, or use -c flag to "just compile".

查看更多
劫难
3楼-- · 2019-09-20 02:02

You declare the Tree constructor & destructor, but you don't show us where you define them (you just say you implement Tree in namespaceB.cc)

Assuming you have defined them, you must ensure you are including both namespaceC.o and namespaceB.o on your link line.

查看更多
登录 后发表回答