关于类定义的问题
我看到以下两个类定义声称是等效的。这是真的吗?如何?谢谢。
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) { }
};
I saw that the following two class definitions are 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) { }
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
第一个分别列出了所有可能性(无参数、一个参数、两个参数)(重载),第二个由于使用 默认参数,完全相同但短得多。
如果变量的初始化不仅仅是为它们赋值,或者您希望根据参数计数拥有完全不同的构造函数,那么第一个仍然有用。
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.
是实现第一个版本的简化方法。它基本上涵盖了第一个中的三个构造函数的所有情况。
Is a simplified way of implementing the first version. It basically covers all the cases of the the three constructors in first one.
后一个示例中的默认值 (r=0) 允许部分或全部省略参数。
因此,一个构造函数方法包含上面示例中的所有三个变体。
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.