前瞻性声明不起作用 [英] forward declaration not working
问题描述
如果我这样做,我的前向声明将不起作用:
My forward declaration doesnt work if i do it like this:
class Manager::TagManager;
namespace UI
{
class Example
{
public:
...
Manager::TagManager* tagManager_;
};
}
表示使用未定义的类型.但是,它的工作原理如下:
it says use of undefined type. However it works fine like so:
namespace Manager
{
class TagManager;
}
//same stuff follows
那有什么区别? 是"class Manager :: TagManager;"不是在名称空间管理器中声明TagManager?
So whats the difference? is "class Manager::TagManager;" not a declaration of TagManager in namespace Manager?
推荐答案
一个反问:您希望编译器如何知道class Manager::TagManager
是命名空间Manager
中的类TagManager
的声明还是的声明.将类Manager
嵌套在类TagManager
中?编译器以前从未听说过Manager
.不知道它是类还是名称空间.这就是编译器试图通过该错误消息告诉您的内容.实际上,它假定Manager
是尚未定义的类类型(不是名称空间).
A rhetorical question: how would you expect the compiler to know whether class Manager::TagManager
is a declaration of class TagManager
in namespace Manager
or a declaration of nested class TagManager
in enclosing class Manager
? The compiler never heard about Manager
before. It has no idea whether it is a class or a namespace. This is what the compiler is trying to tell you by that error message. It actually assumes that Manager
is a class type (not a namespace), which has not been defined.
但是,即使知道Manager
是什么,它仍然无法正常工作.在C ++中,像Name1::Name2
这样的合格名称只能用于引用现有(即已经声明的)实体.您不能使用限定名称来声明 new 实体.
However, even if it knew what Manager
was, it still wouldn't work. In C++ qualified names like Name1::Name2
can only be used to refer to existing (i.e. already declared) entities. You cannot use qualified names to declare new entities.
这意味着只能通过重新打开该名称空间来完成对属于该名称空间的实体的前向声明.嵌套在类中的实体的前向声明只能在封闭类的定义内进行.
That means that a forward declaration of an entity that belongs to a namespace can only be done by reopening that namespace. A forward declaration of an entity that is nested into a class can only be done inside the definition of the enclosing class.
使用名称空间中的实体相对容易,因为您可以根据需要重新打开名称空间多次.使用班级中的嵌套实体,您只有一次机会.
With entities in namespaces it is relatively easy, since you can reopen namespaces as many times as you want. With nested entities in classes you get only one chance.
这篇关于前瞻性声明不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!