C++;函数,我可以为对象提供什么默认值? 我是C++编程新手,所以请不要太苛刻了。下面的例子对我的问题进行了简单的描述。假设我在头文件中有此函数声明: int f(int x=0, MyClass a); // gives compiler error

C++;函数,我可以为对象提供什么默认值? 我是C++编程新手,所以请不要太苛刻了。下面的例子对我的问题进行了简单的描述。假设我在头文件中有此函数声明: int f(int x=0, MyClass a); // gives compiler error,c++,function,object,default,C++,Function,Object,Default,编译器会抱怨,因为具有默认值的参数后面的参数也应该具有默认值 但第二个参数的默认值是什么 其思想是,如果其余参数与特定情况无关,则可以使用少于两个参数调用该函数,因此应满足以下所有要求: MyClass myObj; // create myObj as an instance of the class MyClass int result=f(3,myObj); // explicit values for both args int result=f(3);//第一个参数显式,第二个参数默

编译器会抱怨,因为具有默认值的参数后面的参数也应该具有默认值

但第二个参数的默认值是什么

其思想是,如果其余参数与特定情况无关,则可以使用少于两个参数调用该函数,因此应满足以下所有要求:

MyClass myObj; // create myObj as an instance of the class MyClass
int result=f(3,myObj); // explicit values for both args
int result=f(3);//第一个参数显式,第二个参数默认

int result=f();//两个的默认值都是

您所能做的就是

int f(MyClass a, int x=0);

在这种情况下,您可以使用一个参数(MyClass)和默认的第二个参数调用函数,也可以使用两个显式参数(MyClass,int)调用函数。

我认为您可以执行以下任一操作:

int f(MyClass a, int x=0); // reverse the order of the parameters
int f(int a=0, MyClass a = MyClass()) // default constructor
你可以做一个

int f(int x=0, MyClass a = MyClass());

并根据需要添加构造函数参数。

您可能还想考虑提供重载而不是默认参数,但针对特定的问题,因为<代码> 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 <代码> const引用)< /p>是否可以更改<代码> int f(int x=0,MyClass a);<代码>到

intf(MyClass a,intx=0)人们不会对这样做苛刻:-,但是C++会。出于好奇:你为什么选择学习C++?
int f( MyClass a ) {      // allow the user to provide only the second argument
   f( 0, a );
}