[英]hiding inner class implementation using namespace
I am developing a library and a would like to provide my users a public interface separate from the real implementation that is hidden in a namespace. 我正在开发一个库,并希望为我的用户提供一个公共接口,与隐藏在命名空间中的实际实现分开。 This way, I could change only the class HiddenQueue without changing myQueue that will be exposed to users only.
这样,我只能更改HiddenQueue类而不更改仅向用户公开的myQueue。
If I put the C++ code of HiddenQueue in the myQueue.cpp file the compiler complains saying _innerQueue has incomplete type. 如果我将HiddenQueue的C ++代码放在myQueue.cpp文件中,编译器会抱怨说_innerQueue的类型不完整。 I thought that the linker was able to resolve this.
我认为链接器能够解决这个问题。 What I am doing wrong here?
我在这做错了什么?
// myQueue.h
namespace inner{
class HiddenQueue;
};
class myQueue{
public:
myQueue();
);
private:
inner::HiddenQueue _innerQueue;
};
///////////////////////////
// myQueue.cpp
namespace inner{
class HiddenQueue{};
};
The compiler needs to know the exact memory layout of an object by looking at the header file it's defined in. 编译器需要通过查看它定义的头文件来了解对象的确切内存布局。
Your code says that class MyQueue
has a member of type InnerQueue
, which will be part of the memory layout of MyQueue
objects. 您的代码表示,类
MyQueue
有一个类型的成员InnerQueue
,这将是内存布局的一部分MyQueue
的对象。 Therefore, to deduce the memory layout of MyQueue
it needs to know the memory layout of InnerQueue
. 因此,要推断出
MyQueue
的内存布局,需要了解InnerQueue
的内存布局。 Which it does not, because you say "oh well, it's defined elsewhere". 它没有,因为你说“哦,它在其他地方定义”。
What you are trying to do is closely related to "the PIMPL idiom "/"compiler firewall" technique. 您要做的是与“ PIMPL 习惯用法 ”/“编译器防火墙”技术密切相关。
To solve the problem, you must either include HiddenQueue.h in your header or declare _innerqueue as a pointer: 要解决此问题,您必须在标头中包含HiddenQueue.h或将_innerqueue声明为指针:
class myQueue {
public:
myQueue();
private:
inner::HiddenQueue* _pinnerQueue;
};
Using a pointer is possible because a pointer has a known memory size (dependent on your target architecture), therefore the compiler doesn't need to see the full declaration of HiddenQueue
. 使用指针是可能的,因为指针具有已知的内存大小(取决于您的目标体系结构),因此编译器不需要查看
HiddenQueue
的完整声明。
To be able to make a member of a class, you need to have a definition for it and not only a declaration. 为了能够成为类的成员,您需要为其定义,而不仅仅是声明。 (A declaration is enough for a pointer or a reference to the class).
(对于指针或对类的引用,声明就足够了)。
You need to provide pointer to _innetQueue rather then the object itself: 您需要提供指向_innetQueue的指针,而不是对象本身:
std::auto_ptr<inner::HiddenQueue> _innerQueue;
Search form pimpl ideom or d-pointer 搜索表格pimpl ideom或d-pointer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.