首页 > 解决方案 > 为什么教科书使用一个初始化列表作为operator-(complex a)的返回值?

问题描述

我正在阅读一本(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);

标签: c++classconstructoroperator-overloadinginitializer-list

解决方案


你必须有

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

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

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

相反,您将返回 a complex-a.imag()因为逗号运算符仅返回最后一个值。本质上,代码与

return -a.imag();

为了更明确,作者可以写

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

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


推荐阅读