为什么教科书使用初始化列表作为操作员的返回值(复杂A)
Why does the textbook uses an initializer list as the return value of 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
。如果您尝试使用
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
构造函数,并返回一个新对象。
相关文章:
- 从python中调用C++函数并获取返回值
- 为什么模板类中的对象不能返回值
- 返回值优化:显式移动还是隐式
- lock_guard是否保护返回值
- 调用CreateProcess()并获取字符串的返回值
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 查找 GCD:并非所有控制路径都返回值
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 如何从 std::thread 返回值
- 将返回值从 exe 传递到 bat,并将其传递给 C# 中的进程
- 方法错误"not all control paths return a value"和方法不返回值
- 如何读取 C++ SAFEARRAY**,该 SAFEARRAY** 是 COM 互操作的结果,其中 C# 返回值为
- 对fread的返回值感到困惑
- 程序不向函数返回值
- 如何在另一个函数中使用返回值作为参数?
- 如何使用 uint64_t 键类型从 std::map<int, std::string> 返回值?
- 为什么教科书使用初始化列表作为操作员的返回值(复杂A)
- 如何将c 返回值列表或其他复杂类型的QML列表