Calling another constructor when constructing an object with const members

前端 未结 4 1935
谎友^
谎友^ 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:14

    Where to put the results of myfunc so it can be set and used from different mem-initializers? How about in a default argument?

    class A
    {
    private:
        struct InitData;
    public:
        A(int b, InitData data=InitData());
        A(int b, int c, int d) : b(b), c(c), d(d) { };
    
        const int b;
        const int c;
        const int d;
    };
    
    struct A::InitData
    {
        int setup(int b);
        int c;
        int d;
    };
    
    inline int A::InitData::setup(int b)
    {
        myfunc(b, &c, &d);
        return b;
    }
    
    inline A::A(int b_, InitData data)
        : b(data.setup(b_)),
          c(data.c),
          d(data.d)  {}
    
    A a(0);
    

    Since the made up type is private and has no conversions, there's little risk of accidentally using it or abusing it.

提交回复
热议问题