gpt4 book ai didi

c++ - 在另一个类中访问静态常量。

转载 作者:行者123 更新时间:2023-11-28 03:00:23 24 4
gpt4 key购买 nike

在类中声明和定义的静态常量变量。如何在同一项目中另一个类的私有(private)访问中访问它。是否可以?

//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;
};

关于c++ - 在另一个类中访问静态常量。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20994516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com