c++ - 如何在 C++ 中用更少的空间定义类字段/方法

标签 c++ header-files

这是我的标题:

#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/

相关文章:

c++ - 为什么我不能通过在 cpp 中使用新运算符传递指针来更改值?

c - 为什么排除标准库后没有报错?

c++ - 在多个 Cpp 文件中使用变量

c++ - Caffe 示例代码中的 "TEST"变量有什么作用?

c++ - 节点数组声明

c++ - 为什么在 .cpp 中使用 #include<.hpp>,而不是在 .hpp 中使用 <.cpp>?

C++ - 导出 C++ 库公共(public)部分的正确方法

linux - 事件.h : No such file or directory even when libevent-dev is installed

c++ - 如何在 C/C++ 中的一个 unsigned char 中生成两个随机 1?

c++ - 如何区分存储在模板类中的类型