是否可以保证输入<Type>实数时复杂对象的虚部设置为零?
Is there any guarantee that complex<Type> object's imaginary part is set to zero when a real number is input?
在我的环境(g++ 5.4.0(中,一个代码
complex<double> cmp;
cin >> cmp; //input 3 or (3) (not (3,0))
cout << "cmp = " << cmp << "n";
给我结果:
cmp = (3,0) //imaginary part is automatically set to 0
有没有人有书面证据证明这种行为?N4140(§ 26.4.6-12;第921页(说
Effects: Extracts a complex number x of the form: u, (u), or (u,v),
where u is the real part and v is the imaginary part (27.7.2.2).
但这并不意味着形式u
或(u)
的输入会使对象的虚部0
。
您可以在可靠的 MSDN 示例 (https://msdn.microsoft.com/ja-jp/library/mt771459.aspx#operator_gt__gt_( 中看到此行为,但即使这样也不会做出明确的解释。
草稿说"u
是真实的部分",我只输入真实的部分。我认为在决定将什么样的值设置为虚部时存在歧义。当然,u
的虚构部分是0
的,但我认为这并不能保证什么。
该标准的意图很可能是它应该起作用,即使仔细检查的文本没有明确说明。在实践中,代码将与已知的实现一起使用。
有一份现有的缺陷报告要求委员会澄清其意图是已经实施的:
#2714 复杂流提取未指定
如果你看一下实现(https://gcc.gnu.org/onlinedocs/gcc-4.6.3/libstdc++/api/a00812_source.html(
00486 template<typename _Tp, typename _CharT, class _Traits>
00487 basic_istream<_CharT, _Traits>&
00488 operator>>(basic_istream<_CharT, _Traits>& __is, complex<_Tp>& __x)
00489 {
00490 _Tp __re_x, __im_x;
00491 _CharT __ch;
00492 __is >> __ch;
00493 if (__ch == '(')
00494 {
00495 __is >> __re_x >> __ch;
00496 if (__ch == ',')
00497 {
00498 __is >> __im_x >> __ch;
00499 if (__ch == ')')
00500 __x = complex<_Tp>(__re_x, __im_x);
00501 else
00502 __is.setstate(ios_base::failbit);
00503 }
00504 else if (__ch == ')')
00505 __x = __re_x;
00506 else
00507 __is.setstate(ios_base::failbit);
00508 }
00509 else
00510 {
00511 __is.putback(__ch);
00512 __is >> __re_x;
00513 __x = __re_x;
00514 }
00515 return __is;
00516 }
您可以看到,在s
或(s)
是您在键盘上键入的格式的情况下__x
您的复合体被分配给__re_x
(第 505 行或 513 行(,我们可以将其视为简单起见double
。
快速查看operator=
会告诉您虚部是默认构造的。
00230 complex<_Tp>::operator=(const _Tp& __t)
00231 {
00232 _M_real = __t;
00233 _M_imag = _Tp();
00234 return *this;
00235 }
这意味着您唯一的保证是虚部将被默认构造(在 GCC 上(。 对于大多数类型,这转换为0
初始化。
相关文章:
- Rapidjson 遍历并获取复杂 JSON 对象成员的值
- 当覆盖映射中的复杂对象键时,旧对象将被删除(C++)
- 是否可以保证输入<Type>实数时复杂对象的虚部设置为零?
- 如何查看复杂度为 O(1) 的字符串流对象中的最后一个字符
- 如何通过 COM 互操作访问复杂对象的属性?
- 将复杂对象从 C# 传递到C++
- 用于复杂对象的MPI共享内存
- 使用for_each打印复杂对象
- 如何初始化复杂对象的数组
- 如何使用复杂构造函数分配对象
- 避免在C++循环中循环中复杂对象时最小化范围效率低下的技术
- 将复杂对象传递给 c++ 中的函数,但数组订阅运算符无法正常工作
- 为复杂对象初始化选择哪种设计
- 如何在 gdb 中观察复杂对象
- 向QML公开复杂的Qt对象C++
- 如何使用数组通过引用对对象进行排序?(以一种不那么愚蠢/复杂的方式.)
- 在C++中保存复杂对象的方法
- 将二进制文件用于复杂对象C++
- 使用mmap序列化复杂对象
- 当一个std::vector对象在堆栈中而另一个在堆中时,vector的交换函数的时间复杂度为O(1)或O(n)