为什么教科书使用初始化列表作为操作员的返回值(复杂A)

Why does the textbook uses an initializer list as the return value of operator-(complex a)?

本文关键字:返回值 复杂 操作员 教科书 初始化 列表 为什么      更新时间:2023-10-16

我正在阅读一本教科书(bjarne stroustrup(的定义 complex

class complex {
    double re, im; // representation: two doubles
public:
    complex(double r, double i) :re{r}, im{i} {} // construct complex from two scalars
    complex(double r) :re{r}, im{0} {}           // construct complex from one scalar
    complex() :re{0}, im{0} {}                   // default complex: {0,0}
    double real() const { return re; }
    void ral(double d) { re = d; }
    double imag() const { return im; }
    void imag(double d) { im = d; }
    complex& operator+=(complex z) { re+=z.re, im+=z.im; return *this; } // add to re and im
                                                                         // and return the result
    complex& operator-=(complex z) { re-=z.re, im-=z.im; return *this; }

    complex& operator*=(complex); // defined out-of-class somewhere
    complex& operator/=(complex); // defined out-of-class somewhere
};

这本书还定义了复杂的操作:

complex operator+(complex a, complex b) { return a+=b; }
complex operator-(complex a, complex b) { return a-=b; }
complex operator-(complex a) { return {-a.real(), -a.imag()}; } // unary minus
complex operator*(complex a, complex b) { return a*=b; }
complex operator/(complex a, complex b) { return a/=b; }

我不理解上面的第三行,它涉及单一负量。为什么使用初始化列表作为operator-(complex a);的返回值?

是有意义的

您必须有

return {-a.real(), -a.imag()};

因为您想返回从这两个值创建的complex。如果您尝试使用

return -a.real(), -a.imag();

相反,您将返回仅由-a.imag()创建的complex,因为逗号操作员仅返回最后一个值。本质上,代码与

完全相同
return -a.imag();

为了使其更加明确,作者本可以写

return complex{-a.real(), -a.imag()};
//or
return complex(-a.real(), -a.imag());

,但这确实不需要,因为返回值始终转换为返回类型,并且使用初始化列表,它们就像您输入的return_type{ initializers }一样使用。

没有初始化列表,您必须写

complex operator-( complex a ) { return complex( -a.real(), -a.imag() ); }

使用初始化器列表操作员的定义看起来更简单。

在任何情况下,编译器选择构造函数

complex( double, double );

一般而言,该功能应像

一样声明
complex operator-( const complex &a ) { return { -a.real(), -a.imag() }; }

该函数的返回类型是一个 complex对象,因此" Intitializer"列表中的那些参数被推断为complex构造函数,并返回一个新对象。