我正在尝试从其他文件中不同类的另一个static const
字段的状态(的一部分)初始化const static
字段的状态。
在一个简化的示例中:
// object.h
class Object {
public:
Object(std::string s)
: s(s)
{}
private:
std::string s;
};
// a.h
#include "object.h"
class A {
public:
static const Object o;
};
// a.cpp
#include "a.h"
const Object A::o { "ObjectToCopyFrom" };
// b.h
#include "object.h"
class B {
public:
static const Object o;
}
// b.cpp
#include "a.h"
const Object B::o { A::o };
根据我的经验,我发现B::o
无法从A::o
初始化。它可以编译,但是std::string B::o
为空。我是在做错什么,还是根本不可能?还是对于相互依赖的static const
字段有更好的设计策略?
最佳答案
从C++ 17开始,可以在相应的头文件中的类声明中使用inline
成员变量。这避免了在单个源文件中定义这些成员的需求,从而避免了与不同翻译单元的评估顺序有关的任何歧义。
另外,在给出的示例中,您需要将A::o
设置为public
成员,以便B
类使用它(默认情况下,类成员是private
)。
这是您问题的可能的“仅 header ”解决方案:
// object.h
#include <string>
class Object {
public:
Object(std::string s_arg) // IMHO, using argument names same as members is not a good idea!
: s(s_arg)
{ }
private:
std::string s;
};
// a.h
#include "object.h"
class A {
public: // The "o" member MUST be public in order for the initialization in "B" to work!
static inline const Object o{ "ObjectToCopyFrom" };
};
// b.h
#include "a.h" // Need to include the "a.h" header to get the definition of "class A"
class B {
static inline const Object o{ A::o };
};
关于c++ - 有没有办法从不同类中的另一个const静态字段初始化const静态字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64369527/