简体   繁体   中英

Scope of DataType declared in Namespace

Sample.h

namespace Testing
{
    enum Type
    {
        DATA = 0,
        MORE_DATA
    };
}

Now in Sample2.h, using the same namespace, can I access the DataType defined in Sample.h, without including it?

namespace Testing
{
    Type test;
}

The question has come up, because I have files that implement this, and seem to build with no problem. Another user is trying to build, but reports that he has to #include "Sample.h" in Sample2.h in order to build.

Forward enum declarations are not supported in most current compilers. It is a planned feature of up coming C++0x. You can create pointers to Type probably , but cannot instantiate, this is compatible with other types (structs and classes) as well.

Ow, my bad, I saw it wrong i guess. Anyway, read the others and read this as well. Headers are not compiled stand alone. Therefore, if you don't include a required heading in your header and included that in the cpp file you will not run into any errors. As long as all the cpp files contain both headers with the required order there will be no problems at all. However, this is not a good idea, it is best to include any necessary files within your header and use header guards to ensure they are not added twice. I hope this makes sense.

Most likely the files build because some earlier include file is including Sample.h for you. When the earlier include file is omitted (or moved after Sample2.h) the files will no longer compile.

Yes, you will need to include Sample.h within Sample2.h. The definition of Type is not visible to the compiler within Sample2.h simply because the namespace name is the same within the 2 files.

The only thing you gain by having the same namespace names in the 2 files is that Type does not need to have its namespace stated explicitly in Sample2.h. For instance, if the 2 namespaces were not the same:

Sample.h

namespace Testing
{
    enum Type
    {
        DATA = 0,
        MORE_DATA
    };
}

Sample2.h

#include "Sample.h"

namespace Testing1
{
    Testing::Type test;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM