Right way to conditionally initialize a C++ member variable?

前端 未结 6 1086
执念已碎
执念已碎 2020-12-30 07:18

I\'m sure this is a really simple question. The following code shows what I\'m trying to do:

class MemberClass {
public:
    MemberClass(int abc){ }
};

clas         


        
6条回答
  •  时光说笑
    2020-12-30 07:59

    Use the initializer list syntax:

    class MyClass {
    public:
        MemberClass m_class;
        MyClass(int xyz) : m_class(xyz == 42 ? MemberClass(12) : MemberClass(32)
                                   /* see the comments, cleaner as xyz == 42 ? 12 : 32*/)
        { }
    };
    

    Probably cleaner with a factory:

    MemberClass create_member(int x){
       if(xyz == 42)
         return MemberClass(12);
        // ...
    }
    
    //...
     MyClass(int xyz) : m_class(create_member(xyz))
    

提交回复
热议问题