我是C++编程的新手,所以现在请不要太苛刻:)。下面的例子说明了我的问题的最小描述。假设我在一个头文件中有这个函数声明:
int f(int x=0, MyClass a); // gives compiler error编译器会抱怨,因为带有默认值的参数后面的参数也应该有默认值。
但是我可以给第二个参数提供多大的默认值呢?
其思想是,如果其余的参数与特定情况无关,则可以使用少于两个参数调用函数,因此应执行以下所有操作:
MyClass myObj; // create myObj as an instance of the class MyClass
int result=f(3,myObj); // explicit values for both argsint result=f(3); // explicit for first, default for second arg
int result=f(); // defaults for both
发布于 2012-03-28 22:23:25
您可能还希望考虑提供重载而不是默认参数,但对于您的特定问题,因为MyClass类型具有默认构造函数,并且如果它在您的设计中有意义,您可以默认为:
int f(int x=0, MyClass a = MyClass() ); // Second argument default
// is a default constructed object如果您愿意,可以通过手动添加重载在用户代码中获得更大的灵活性:
int f( MyClass a ) { // allow the user to provide only the second argument
f( 0, a );
}此外,您应该考虑在接口中使用引用(通过常量引用获取MyClass )
发布于 2012-03-28 22:21:24
我认为您可以执行以下任一操作:
int f(MyClass a, int x=0); // reverse the order of the parameters
int f(int a=0, MyClass a = MyClass()) // default constructor发布于 2012-03-28 22:20:37
你能做的最多就是
int f(MyClass a, int x=0);在这种情况下,您可以使用一个参数(MyClass)和默认的第二个参数调用函数,也可以使用两个显式参数(MyClass,int)调用函数。
https://stackoverflow.com/questions/9909444
复制相似问题