c++ - 有没有办法从不同类中的另一个const静态字段初始化const静态字段?

标签 c++ static initialization constants field

我正在尝试从其他文件中不同类的另一个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/

相关文章:

c++ - CRT 库 : wrong version

java - 从 BroadcastReceiver 获取方法来更新 UI

java - Java中静态方法中调用非静态方法

swift - 初始化后如何更改实例变量?

java - 为什么此 FXML 应用程序中不显示 TreeView 根?

C++如何将比率转换为 double

C++ 从具有取消引用类型类型的函数返回引用?

c++ - 使用 GetWindowText 将文本框保存到文件中:std::string 到 LPWSTR

c++ - 我可以在 C++ 运行时初始化静态 const 成员吗?

c# - 初始化列表属性的最佳实践?