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

前端 未结 6 1128
执念已碎
执念已碎 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:53

     MyClass(int xyz) : m_class(xyz==42 ? 12 : 32) {}
    

    To answer your revised question, that get a bit tricky. The simplest way would be to make m_class a pointer. If you really want it as a data member, then you have to get creative. Create a new class (it's best if it's defined internal to MyClass). Have it's ctor be the function that needs to be called. Include it first among the declarations of data members (this will make it the first instaniated).

    class MyClass 
    {
         class initer { public: initer() {
                        // this must happen before m_class is created
                        do_something();                        
                        }
                       }
    
        initer     dummy;
    public:
    
        MemberClass m_class;
        MyClass(int xyz) : m_class(xyz==42? 12 : 43)
        {
            // dummy silently default ctor'ed before m_class.
        }
    };
    

提交回复
热议问题