简体   繁体   English

如何初始化不是静态的const成员

[英]How to initialize const member , that are not static

I know how to initialize const member in the initializer list, but that requires to know the value to be assigned already when calling the constructor. 我知道如何在初始化列表中初始化const成员,但这需要知道在调用构造函数时已分配的值。 From what I understand, in java it's possible to initialize a final member in the constructor body, but I haven't seen an equivalent in c++ ( Java's final vs. C++'s const ) 据我了解,在Java中可以在构造函数主体中初始化最终成员,但我还没有看到C ++中的等效成员( Java的最终版本与C ++的const

But what to do when the initialization is relatively complex? 但是,当初始化相对复杂时该怎么办? The best I could come up, is to have an initialization function that returns directly an instance. 我能想到的最好的办法是拥有一个直接返回实例的初始化函数。 Is there something more concise? 还有更简洁的东西吗?

Here is an example ( https://ideone.com/TXxIHo ) 这是一个示例( https://ideone.com/TXxIHo

class Multiplier
{
   const int mFactor1;
   const int mFactor2;
   static void initializationLogic (int & a, int & b, const int c )
   {
       a = c * 5;
       b = a * 2;
    }

  public:
   Multiplier (const int & value1, const int & value2)
     : mFactor1(value1), mFactor2(value2)
     {};
   /*
   //this constructor doesn't initialize the const members
   Multiplier (const int & value)
     {
        initializationLogic(mFactor1,mFactor2, value);
     };
    */
   //this initializes the const members, but it's not a constructor
   static Multiplier getMultiplierInstance (const int & value)
   {
       int f1, f2;
       initializationLogic(f1,f2, value);
       Multiplier obj(f1,f2);
       return obj;
   }

You can delegate object construction to a dedicated constructor accepting an instance of helper class preparing all the necessary parameters: 您可以将对象构造委托给专用的构造函数,该构造函数接受准备所有必要参数的helper类的实例:

 private: class
 Init_Helper final
 {
    private: int m_value1;
    private: int m_value2;

    public: explicit Init_Helper(const int c)
    {
        m_value1 = c * 5;
        m_value2 = m_value1 * 2;
        // more init logic goes here...
    }

    public: int const & Get_Value1(void) const
    {
        return m_value1;
    }

    public: int const & Get_Value2(void) const
    {
        return m_value2;
    }
 };

 public: explicit  Multiplier(const int c)
 :  Multiplier{Init_Helper{c}}
 {}

 private: explicit Multiplier(Init_Helper && helper)
 :  mFactor1{helper.Get_Value1()}, mFactor2{helper.Get_Value2()}
 {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM