这是我的标题:
#ifndef MYCLASSES_H_
#define MYCLASSES_H_
#define ARRAY_SIZE(x) (sizeof((x)) / sizeof((x)[0]))
namespace mynamespace {
class A
{
class B
{
class C
{
void doStuff(B *pB);
}
static const C SOME_ARRAY[];
static const int SOME_ARRAY_COUNT;
}
}
} //namespace mynamespace
#endif /* MYCLASSES_H_ */
这就是 CPP:
#include "myclasses.h"
namespace mynamespace {
void A::B::C::doStuff(A::B *pB)
{
/* ... */
}
const A::B::C A::B::SOME_ARRAY[] = {
/*...*/
};
const A::B::SOME_ARRAY_COUNT = ARRAY_SIZE(
} //namespace mynamespace
我应该怎么做才能使 .CPP 文件中的定义具有更短的名称?这非常麻烦。
最佳答案
Man walks into a doctor. He says "Doctor, my head hurts when I bang it against the wall". Doctor says: "Don't bang your head on the wall and your head will stop hurting".
由于 B 和 C 位于 A 类的私有(private)区域,因此世界无法看到它们。
因此没有必要将它们嵌套在 A 中只是让它们对外界不可见。
执行此操作的简单方法是将它们放在源文件内的匿名 namespace 中。
#ifndef MYCLASSES_H_
#define MYCLASSES_H_
#define ARRAY_SIZE(x) (sizeof((x)) / sizeof((x)[0]))
namespace mynamespace {
class A
{
}
} //namespace mynamespace
#endif /* MYCLASSES_H_ */
这就是 CPP:
#include "myclasses.h"
namespace
{
// This is an anonymouse namespace
// It does not export it symbols outside the compilation unit.
// So only A should be able to see them
class B
{
static const C SOME_ARRAY[];
static const int SOME_ARRAY_COUNT;
};
class C
{
void doStuff(B *pB);
};
}
void C::doStuff(B *pB)
{
/* ... */
}
const C B::SOME_ARRAY[] = {
/*...*/
};
const B::SOME_ARRAY_COUNT = ARRAY_SIZE(
关于c++ - 如何在 C++ 中用更少的空间定义类字段/方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9077313/