c++ - 为什么教科书使用一个初始化列表作为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);
?
解决方案
你必须有
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 }
。
推荐阅读
- wordpress - 如何从 Wordpress 二十二十页眉中删除链接?
- html - 在运行时在 Xamarin 表单中绑定标签的 FormattedString 跨度
- typo3 - TYPO3 9.5.21 起始页 /index/ 在 URI
- javascript - 如何将 ViewModel 从 MVC Html 传递给 Jquery?
- angular - ng-template 无法读取复选框上未定义的属性“已选择”
- javascript - 阻止赛普拉斯在每次之前执行 BeforeEach()
- reactjs - 传播不可迭代实例的无效尝试。为了可迭代,非数组对象必须有一个 [Symbol.iterator]() 方法 React Native
- python - 在 PlainTextEdit 中显示日志文件的实时时间
- docker - Docker:在 Linux 上无法在 @INC 中找到 Tk.pm(您可能需要安装 Tk 模块)
- algorithm - 如果一个物体是一个圆,你需要知道的最少信息是多少?