开发者

question on class definitions

I saw that the following two class definitions 开发者_如何学Care claimed to be equivalent. Is that true? How? Thanks.

class  complex{
double re, im;
public:
  complex( ): re(0) , im(0) { }
  complex (double  r): re(r), im(0)  { }
  complex (double  r, double i): re(r),   im(i) { }
};
class  complex{
  double re, im;
  public:
    complex (double  r=0, double i=0): re(r),   im(i) { }
};


The first one lists all the possibilities (no parameter, one parameter, two parameters) separately (overloading), the second one only needs one function because of usage of default parameters, which is exactly the same but much shorter.

The first one is still useful if initialization of variables is more than just assigning a value to them or you want to have completely different constructors depending on the parameter count.


Strictly speaking, the are not equivalent (after all, the second has only one constructor while the first has three), but they behave equally. A constructor with nonzero arguments providing default values for all of them qualifies as a default constructor.


Yes. They're equivalent. But the second one is better in my opinion,as it's compact, taking advantage of one C++ feature called default argument.


class  complex{
  double re, im;
  public:
    complex (double  r=0, double i=0): re(r),   im(i) { }
};

Is a simplified way of implementing the first version. It basically covers all the cases of the the three constructors in first one.


The default values (r=0) in the latter example allow for the arguments to be partially or fully omitted. Thus the one constructor method comprises all three variants from the top example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜