//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 ?
我必须考虑MISRA编写代码 (问题是用静态const替换所有CONSTANT MACRO 但是接着如何在另一个文件中访问这些静态const,而这些其他数据成员再次使用静态const)
这里的Namespace创建并提供从它到任何类成员的变量看起来很干净。这可能是最好的方法,但我必须考虑MISRA规则,当我们使用命名空间时,我们必须使用'使用'指令(使用命名空间NameoftheNamespace),这也是MISRA不允许的......但从根本上说它看起来不可能给一个私有静态const变量到另一个不同的类(不使用命名空间)....意见????
答案 0 :(得分:2)
您不想访问私有静态常量变量,您希望Replace a constant macro with static const
。
宏之前是公开的,为什么变量现在应该是私有的?
无论如何,如果你仍然想要私人方法,还有另一种选择(以高耦合为代价):让他们成为朋友!
//A.h
class A {
static int _A;
friend class B; // there's no need to include B.h
};
//A.cpp
int A::_A = 10;
// B.h
class B {
static int _B;
};
//B.cpp
#include "A.h"
int B::_B = A::_A;
还有另一种选择,它将介于这两者之间:
// constants.h
namespace myMacros {
extern static const int _A;
}
// constants.cpp
const int myMacros::_A = 10;
答案 1 :(得分:1)
您可以使用公共'getter'函数访问私有变量。如果需要访问静态变量,则必须使用静态方法。
class A {
public:
inline static uint8_t GetA() { return AVar; }
}
答案 2 :(得分:0)
由于变量AVar
位于A类的私有部分,因此B类无法访问它。如果您需要B类访问AVar,则需要更改代码。最好将它移到A类的公共部分。