开发者

Forward declaring classes in namespaces

I was rather surprised to learn that I couldn't forward declare a class from another scope using the scope resolution operator, i.e.

class someScope::someClass;

Instead, the full declaration has to be used as follows:

namespace
{
    class someClass;
}

Can someone explain why this is the case?

UPDATE: To clarify, I am as开发者_Python百科king why this is the case.


You can't declare a class outside its namespace, because the compiler could not be aware of the type of someScope.

namespace{ } is required to declare the existence of namespace, and then, declare class someClass into your scope.


Seems as though the answer lies in the C++ specification:

3.3.5 "Namespace scope" in the standard.

Entities declared in a namespace-body are said to be members of the namespace, and names introduced by these declarations into the declarative region of the namespace are said to be member names of the namespace.

A namespace member can also be referred to after the :: scope resolution operator (5.1) applied to the name of its namespace or the name of a namespace which nominates the member’s namespace in a using-directive;


I am not sure why. Maybe because, in your first code snippet, someScope is undeclared. It can be a namespace, or a class name. If someScope is a class name, you can't independently forward declare a class member of another class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜