How to use class defined in a separate header with

2019-08-10 22:35发布

问题:

I have a namespace in which I'd like to define a class. The class is rather complex so I'd rather define it in a separate header file, but even the simplest code gives me an "undefined reference" error.

main.cpp

#include <iostream>
namespace A {
    #include "C.hpp"
}

int main()
{
    A::C foo;
    std::cout << foo.member << std::endl;
    return 0;
}

C.hpp

class C {
    public:
     C();
     int member;
}

C.cpp

C::C()
{
    this->member = 10;
}

When I run g++ C.cpp main.cpp I get "main.cpp:(.text+0x10): undefined reference to `A::C::C()'" error. I suppose that it's the C::C() definition of the constructor that is somehow wrong, but I'm uncertain how to fix it.

回答1:

namespace A {
    #include "C.hpp"
}

This is a very odd thing to do.

This places everything declared in the header inside a namespace called A; specifically, it gives you a declaration of A::C, which is a different class to the ::C you get when you include the header without a surrounding namespace.

You have provided a definition for ::C::C(); but main.cpp requires a definition for A::C::C(), since that is the class it uses. That's not defined anywhere, hence the error.

Either put C properly into namespace A by moving the namespace to the header file (and fix C.cpp to use that namespace), or get rid of namespace A.



回答2:

You have to define C's constructor inside namespace A too:

namespace A
{
    C::C()
    {
        this->member = 10;
    }
}