use*_*609 5 c++ default function object
我是C++编程的新手,所以请不要太苛刻了:) 以下示例说明了我的问题的最小描述.假设我在头文件中有这个函数声明:
int f(int x=0, MyClass a); // gives compiler error
Run Code Online (Sandbox Code Playgroud)
编译器会抱怨,因为具有默认值的参数后面的参数也应该具有默认值.
但是我可以给出第二个参数的默认值是什么?
我们的想法是,如果其余的与特定情况无关,则可以使用少于两个args调用该函数,因此以下所有内容应该:
MyClass myObj; // create myObj as an instance of the class MyClass
int result=f(3,myObj); // explicit values for both args
Run Code Online (Sandbox Code Playgroud)
int result=f(3); // explicit for first, default for second arg
int result=f(); // defaults for both
您可能还想考虑提供重载而不是默认参数,但对于您的特定问题,因为该MyClass
类型有一个默认构造函数,并且如果它在您的设计中有意义,您可以默认为:
int f(int x=0, MyClass a = MyClass() ); // Second argument default
// is a default constructed object
Run Code Online (Sandbox Code Playgroud)
如果您愿意,您可以通过手动添加重载来获得用户代码的更大灵活性:
int f( MyClass a ) { // allow the user to provide only the second argument
f( 0, a );
}
Run Code Online (Sandbox Code Playgroud)
您还应该考虑在接口中使用引用(MyClass
通过 const 引用获取)