Expand scope of a variable initialized in a if/else sequence

后端 未结 3 787
轮回少年
轮回少年 2020-12-07 03:22

I\'m writing a piece of code in which I\'d like to use a different constructor of a class depending on a condition. So far I\'ve used if and else s

3条回答
  •  悲&欢浪女
    2020-12-07 04:04

    try the following :)

    MyClass my_object = my_boolean ? MyClass(arg1) : MyClass(arg1,arg2);
    

    Take into account that this code will work even if the class has no default constructor.

    Here is a demonstrative example

    #include  
    #include 
    #include 
    
    int main () 
    {
        struct Point
        {
            Point( int x ) : x( x ) {}
            Point( int x, int y ) : x( x ), y( y ) {}
            int x = 0;
            int y = 0;
        };
    
        std::srand( ( unsigned )std::time( 0 ) );
    
        Point p = std::rand() % 2 ? Point( 1 ) : Point( 1, 2 );
    
        std::cout << "p.x = " << p.x << ", p.y = " << p.y << std::endl;  
    
        return 0; 
    }
    

    I have gotten the following output

    p.x = 1, p.y = 2
    

    What output have you gotten? :)

提交回复
热议问题