Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

c++ - Why can't I forward-declare a class in a namespace using double colons?

class Namespace::Class;

Why do I have to do this?:

namespace Namespace {
    class Class;
}

Using VC++ 8.0, the compiler issues:

error C2653: 'Namespace' : is not a class or namespace name

I assume that the problem here is that the compiler cannot tell whether Namespace is a class or a namespace? But why does this matter since it's just a forward declaration?

Is there another way to forward-declare a class defined in some namespace? The syntax above feels like I'm "reopening" the namespace and extending its definition. What if Class were not actually defined in Namespace? Would this result in an error at some point?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're getting correct answers, let me just try re-wording:

class Namespace::Class;

Why do I have to do this?

You have to do this because the term Namespace::Class is telling the compiler:

...OK, compiler. Go find the namespace named Namespace, and within that refer to the class named Class.

But the compiler doesn't know what you're talking about because it doesn't know any namespace named Namespace. Even if there were a namespace named Namespace, as in:

namespace Namespace
{
};

class Namespace::Class;

it still wouldn't work, because you can't declare a class within a namespace from outside that namespace. You have to be in the namespace.

So, you can in fact forward declare a class within a namespace. Just do this:

namespace Namespace
{
    class Class;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...