默认参数和构造函数

默认参数和构造函数

本文介绍了默认参数和构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 如果想要将默认参数传递给构造函数,那么 最好的方法是什么,(除了重载构造函数并写一个 辅助函数) )? MyClass MyClass(int,int); MyClass MyClass(int,int,float); void helper_func (int,int,float = PI); 我的意思是有人可以写这样的东西: MyClass c * =新的MyClass(int arg1,int arg2,float arg3 = PI)? (AFAIK,这是非法的,因为编译器不会理解它。 Tks 解决方案 你试过吗? 这是完全合法的,任何编译器都应该接受它。 class MyClass { MyClass (int,int,float = PI); }; - Karl Heinz Buchegger kb ****** @ gascad.at struct MyClass { MyClass(int i,int j,float k = 3.14){ } }; int main() { MyClass m1(1,2); MyClass m2(1,2,2.28); } HTH, Sharad 这是非法的 - 1)在向构造函数传递参数时不能指定类型 2)您必须将值传递给构造函数以构造 对象 MyClass * c = new MyClass(10,20); MyClass * d = new MyClass(10,20) ,30.0); 问候, Srini If one wants to pass default arguments to a constructor, what is thebest way to do it, (other than overloading the constructor and writing ahelper function)?MyClass MyClass(int, int);MyClass MyClass(int,int,float) ;void helper_func(int,int, float = PI) ;I mean is there anyway one can write something like this :MyClass c* = new MyClass(int arg1, int arg2, float arg3 = PI) ?(AFAIK, this is illegal, as the compiler dosen''t grok it.Tks 解决方案Have you tried it?It is perfectly legal and any compiler should accept it.class MyClass{MyClass( int, int, float = PI );};--Karl Heinz Buchegger kb******@gascad.atstruct MyClass {MyClass(int i, int j, float k = 3.14){}};int main(){MyClass m1(1, 2);MyClass m2(1, 2, 6.28);}HTH,SharadIt is illegal -1) You cannot specify types while passing arguments to a constructor2) You have to pass values to the constructor for constructing anobjectMyClass *c = new MyClass(10, 20);MyClass *d = new MyClass(10, 20, 30.0);Regards,Srini 这篇关于默认参数和构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-01 05:35