Calling another constructor when constructing an object with const members

前端 未结 4 1857
谎友^
谎友^ 2020-12-20 23:20

I have a class with const members, and one constructor which calls another constructor with extra values filled in. Normally I could use a colon initializer for

4条回答
  •  隐瞒了意图╮
    2020-12-21 00:23

    I prefer Kerrek SB's answer, but in your case there is the complication that you can't easily make separate initialisation functions for each member.

    In that case, another solution is to move the members to a base class and initialize that base class with a helper class with non-const members. Your initialization code is moved to the helper class' constructors, and can assign without problems.

    class A_init
    {
      public:
        A_init(int b)
        {
          // do whatever you like with c and d:
          c = ...;
          d = ...;
        }
    
        int c; // Note: non-const
        int d; // Note: non-const
    };
    
    class A_base
    {
       public:
         A_base(int b, A_init init) : b(b), c(init.c), d(init.d) {}
         A_base(int b, int c, int d) : b(b), c(c), d(d) {}
    
         const int b;
         const int c;
         const int d;
    };
    
    class A : public A_base
    {
      public:
        A(int b) : A_base(b, A_init(b)) {}
        A(int b, int c, int d) : A_base(b, c, d) {}
    };
    

    If one wants restrict access to A_init, one can switch to private and declare A a friend.

提交回复
热议问题