简体   繁体   中英

Conditional constructor calling in C++

In the following code

#include <iostream>

enum class motorid{
    M1,
    M2
};
enum class encoderid{
    E1,
    E2
};
class encoder{
public :
    encoder(encoderid eid):Eid(eid){}
private:
    encoderid Eid;
};
class motor{
    public:
    motor(motorid mid):Mid(mid){
        if(mid == motorid::M1){
            e(encoderid::E1);
        }
        e(encoderid::E2);
    }
    private:
    motorid Mid;
    encoder e;
}

I want to initialize encoder class with value based on value given to motor class from main, I don't want to expose the encoder details to main,but I am forced to give the encoder type also. How to achieve this? Since no heap is involved using new and creating object is not an option.

Syntax would be:

motor(motorid mid):Mid(mid), e(mid == motorid::M1 ? encoderid::E1 : encoderid::E2)
{
}

For more complex case (or for readability), creating function might help:

encoderid create_encoderid(motorid mid)
{
    if (mid == motorid::M1){
        return encoderid::E1;
    }
    return encoderid::E2;
}

motor::motor(motorid mid):Mid(mid), e(create_encoderid(mid))
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM