How to set default parameter as class object in c++?

前端 未结 4 700
萌比男神i
萌比男神i 2020-12-30 07:08

I want to set my function with class object parameter set as default. But when I try to do that it fails in compilation.

class base {
 // ...
};

int myfunc(         


        
4条回答
  •  庸人自扰
    2020-12-30 07:55

    A hack or ugly solution would be do a static cast from null:

    #include 
    
    class MyCustomClassType {
      int var;
    
      friend std::ostream &operator<<( 
             std::ostream &output, const MyCustomClassType &my_custom_class_type )
      {
        output << my_custom_class_type.var;
        return output;
      }
    };
    
    void function(
           MyCustomClassType my_custom_class_type = *static_cast( nullptr )
        ) 
    {
      std::cout << my_custom_class_type << std::endl;
    }
    
    /**
     * To build it use:
     *     g++ -std=c++11 main.cpp -o main
     */
    int main (int argc, char *argv[]) {
      function();
    }
    

    But, running this gives you directly a segmentation fault due dereferencing a null pointer. I am not sure when this would be useful.

提交回复
热议问题