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

前端 未结 4 704
萌比男神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:53

    @tenfour answer forgot to mention another possible way. You also define a global variable object which you can construct as you like, then set it as the default value:

    #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;
      }
    };
    
    // C++11 syntax initialization call to the default constructor
    MyCustomClassType _my_custom_class_type{};
    
    void function(MyCustomClassType my_custom_class_type = _my_custom_class_type) {
      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();
    }
    

提交回复
热议问题