C++ 使用另一个类的成员字段初始化成员字段

C++ 使用另一个类的成员字段初始化成员字段,c++,constants,member,C++,Constants,Member,我想用另一个类的成员字段初始化一个成员字段 // a.hpp class A { public: std::string m_protocol_field_end{"\n"}; // should be changeable, therefore no const ... // b.hpp class B { public: const std::string m_protocol_field_end{A::m_protocol_field_end}; // should NO

我想用另一个类的成员字段初始化一个成员字段

// a.hpp
class A {
public:
    std::string m_protocol_field_end{"\n"}; // should be changeable, therefore no const
...

// b.hpp
class B {
public:
    const std::string m_protocol_field_end{A::m_protocol_field_end}; // should NOT be changeable, therefore const
我得到这个错误:

error: invalid use of non-static data member 'A::m_protocol_field_end'

如何解决它?

一种解决方案是在构造函数中取值,例如,如果
类B
更改为:

class B {
public:
    B(const string& protocol_field_end) : m_protocol_field_end(protocol_field_end) {}
    const std::string m_protocol_field_end;
};
这将允许您在代码中执行类似的操作:

const A myA;
const B myB{ myA.m_protocol_field_end };

我想我有一个答案:

const std::string protocol_field_end_default{"\n"};

// a.hpp
class A {
public:
    std::string m_protocol_field_end{protocol_field_end_default}; // should be changeable, therefore no const
...

// b.hpp
class B {
public:
    const std::string m_protocol_field_end{protocol_field_end_default}; // should NOT be changeable, therefore const

好了,现在它不是“单点故障”,但它工作了。

所以
B
也有一个
const
m_协议_字段_end
并且您希望它从
a
的非const
m_协议_字段_end
初始化。是否希望字段作为每个对象中的非静态成员,或者您希望在所有实例之间共享静态成员?您指定
A::m_protocol_field_end
不是
const
,而是可变的,可以更改。那么,在
B
的定义中,不清楚您所说的
A::m_protocol\u field\u end
是什么意思。您是指默认初始值设定项的值吗?您是指某个未命名实例当前具有的值吗?你是否假设只有一个
A
?你无法解决它。没有所谓的
A::m\u protocol\u field\u end
<代码>m_协议_字段_end仅存在于类型为
A
的特定对象中。没有类型为
A
的对象-没有
m\u协议\u字段\u end
。时期这就提出了一个明显的问题:
m\u协议\u字段\u结束
为什么是非静态的?您是否计划在类型为
A
的不同对象中使用不同的
m\u protocol\u field\u end
值?如果我将第一个成员字段设置为A之外的静态字段,该怎么办?然后写const std::string m_protocol_field_end{m_protocol_field_end};在B区?静态自由变量(在名称空间X::Y::)是可更改的吗?只有当它是您想要使用的默认值/初始值时,它才起作用。这里似乎不是这样。现在有多个具有相同值的常量字符串:一个作为全局常量,一个在类型为
B
的每个对象中。似乎您希望去掉
B
字段,或者至少使其在类中保持静态。