访问另一个类中的静态常量

Access static const in another class.

本文关键字:静态 常量 另一个 访问      更新时间:2023-10-16

在类中声明和定义的静态常量变量。如何在同一项目中另一个类的私有访问中访问它。可能吗?

//in some header file
Class A{
    public:
    //some data
    private:
        static const uint8_t AVar =1;
        //other data
};

//in some another header file
Class B{
    static const Bvar; 
};
//here inside Class B it possible to give Bvar  = AVar ? If yes, How ?

在不削弱任一类封装的情况下避免重复魔术值的一种干净方法是将魔术值移动到两个类都可以公开访问的不同位置。

例如:

namespace detail {
    enum MAGIC_NUMBER_T {
        MAGIC_NUMBER = 1
    };
}
class A{
  private:
  static const uint8_t AVar = detail::MAGIC_NUMBER;
};
class B{
     static const uint8_t BVar = detail::MAGIC_NUMBER;
};