c++ - 如何初始化非静态的 const 成员

标签 c++ c++11 constructor constants

我知道如何在初始化列表中初始化 const 成员,但这需要在调用构造函数时知道要分配的值。 据我了解,在 Java 中可以在构造函数主体中初始化最终成员,但我还没有在 C++ 中看到等效项(Java's final vs. C++'s const)

但是初始化比较复杂怎么办呢? 我能想到的最好的办法就是拥有一个直接返回实例的初始化函数。有没有更简洁的东西?

这是一个例子(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;
   }

最佳答案

您可以将对象构造委托(delegate)给专用构造函数,该构造函数接受准备所有必要参数的辅助类实例:

 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()}
 {}

关于c++ - 如何初始化非静态的 const 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48954802/

相关文章:

c++ - 无法开发简单的时钟和日期类

c++ - std::get like(部分)模板特化

c++ - 智能指针 : Does a 'base' part of an object get created?

c++ - 为数组的每个元素调用构造函数

design-patterns - 单例模式中的私有(private)构造函数

c++ - 无法声明和识别全局函数

c++ - 在 C++ 字符串中,为什么在最后一个字符之后,通过索引和 at() 访问时行为不同?

c++ - 什么是复制省略和返回值优化?

java - 构造函数有很多元素。如何重构(工厂模式)

c++ - 抛出类似函数的可变参数宏包装,替换抛出的异常