如何使用在命名空间中的单独标题中定义的类 [英] How to use class defined in a separate header within a namespace
问题描述
我有一个命名空间,我想在其中定义一个类。这个类是相当复杂的,所以我宁愿在一个单独的头文件中定义它,但即使最简单的代码给我一个未定义的引用错误。
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;
}
当我运行 g ++ C.cpp main.cpp
我得到main.cpp :(。文本+ 0x10):未定义的引用`A :: C :: C()'错误。我想这是构造函数的C :: C()定义是不对的,但我不知道如何解决它。
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.
推荐答案
namespace A {
#include "C.hpp"
}
这是一件非常奇怪的事情。
This is a very odd thing to do.
这会将标题中声明的所有内容放在名为 A
;具体来说,它给你一个 A :: C
的声明,这是与 :: C
不同的类
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.
您为 :: C :: C()提供了一个定义
;但 main.cpp
需要定义 A :: C :: C()
,因为它是类使用。
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.
将 C
正确地放入命名空间A
将命名空间移动到头文件(并修复 C.cpp
以使用该命名空间),或除去命名空间A
。
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
.
这篇关于如何使用在命名空间中的单独标题中定义的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!