C++: “Class namespaces”? [duplicate]

2020-02-28 03:56发布

问题:

If in C++ I have a class longUnderstandableName. For that class I have a header file containing its method declaration. In the source file for the class, I have to write longUnderstandableName::MethodA, longUnderstandableName::MethodB and so on, everywhere.

Can I somehow make use of namespaces or something else so I can just write MethodA and MethodB, in the class source file, and only there?

回答1:

typedef longUnderstandableName sn;

Then you can define the methods as

void sn::MethodA() {}
void sn::MethodB() {}

and use them as

sn::MethodA();
sn::MethodB();

This only works if longUnderstandableName is the name of a class. It works even if the class is deeply embedded in some other namespace.

If longUnderstandableName is the name of a namespace, then in the namespace (or source file) where you want to use the methods, you can write

using namespace longUnderstandableName;

and then call methods like

MethodA();
MethodB();

You should be careful not to use a using namespace foo; in header files, because then it pollutes every .cpp file that we #include the header file into, however using a using namespace foo; at the top of a .cpp file is definitely allowed and encouraged.



回答2:

Inside the methods of the classes, you can use the name without qualification, anyway: just drop the longUnderstandableName:: prefix.

In functions inside the class source file that are not methods, I suggest to introduce file-scope static inline functions, like so:

inline type MethodA(type param){
    return longUnderstandableName::MethodA(param);
}

Then you can call MethodA unqualified; due to the inline nature, this likely won't cost any runtime overhead.



回答3:

I'm not sure I'd recommend it, but you could use a macro like:

#define sn LongUnderstandableName

void sn::MethodA(parameters) { ... }
int sn::MethodB(parameters) { ... }

and so on. One of the bad points of macros is that they don't respect scope, but in this case, the scope you (apparently) want is the source file, which happens to correspond (pretty closely) with the scope of a macro.



回答4:

Well, yes, once you understand namespaces.

Instead of naming your class MyBonnieLiesOverTheOcean, instead set up the following:

namespace My { namespace Bonnie { namespace LiesOverThe {
   class Ocean { ... };
} } }

Now, when defining your methods, you put the same namespaces around the whole file, and you write:

Ocean::SomeMethod() ...

When using the class from outside all the namespaces, it's:

My::Bonnie::LiesOverThe::Ocean

If you need to reference a lot of things from some other namespace in some source file, you can use the 'use' directive to ditch the prefixes.