Calling another constructor when constructing an object with const members

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

    You can add a parameters class and use either C++11 constructor delegation or a base class:

    struct parameters {
        int b; int c; int d;
        parameters(int b): b(b), c(), d() {
            myfunc(b, &c, &d);
        }
    };
    
    // constructor delegation
    class A {
    public:
        A(int b): A(parameters(b)) { }
        A(parameters p): b(p.b), c(p.c), d(p.d) { }
    };
    
    // base/wrapper
    class ABase {
        ABase(parameters p): b(p.b), c(p.c), d(p.d) { }
    };
    
    class A: public ABase {
    public:
        A(int b): ABase(parameters(b)) { }
    };
    

提交回复
热议问题