【问题标题】:Why C++ compiler doesn't provide overloaded inserter & extractor functions for class?为什么 C++ 编译器不为类提供重载的插入器和提取器函数?
【发布时间】:2015-08-08 13:39:57
【问题描述】:

考虑以下程序。

#include <iostream>
using std::ostream;
using std::cout;
using std::istream;
using std::cin;
class three_d {
    int i,j,k;
    public:
        three_d(int a,int b,int c) : i(a),j(b),k(c)
        { }
        //friend ostream& operator << (ostream&,const three_d&);
        //friend istream& operator >> (istream&,three_d&);
};
/*ostream& operator << (ostream& o,const three_d& t) {
    o<<t.i<<", ";
    o<<t.j<<", ";
    o<<t.k<<"\n";
    return o;
}
istream& operator >> (istream& stream,three_d &t) {
    cout<<"Enter x,y,z values";
    stream>>t.i>>t.j>>t.k;
    return stream;
}*/
int main() {
    three_d a(1,2,3),b(4,5,6),c(7,8,9);
    cout<<a<<b<<c;
    cin>>a;
    cout<<a;
}

我特意注释掉了重载的 >> &

*[Error] no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'three_d')

[Error] no match for 'operator>>' (operand types are 'std::istream {aka std::basic_istream<char>}' and 'three_d')*

默认情况下,即使对于空类,如果程序员不提供,C++ 编译器也会自动提供以下内容。

1) 构造函数

2) 析构函数

3) 复制构造函数

4) =(赋值)运算符

那么为什么 >> & > &

【问题讨论】:

  • 很少有机会流式传输类的对象状态,否则所有默认函数的概率都很高
  • 对于您提到的运算符,默认行为通常很明显。 &lt;&lt;&gt;&gt; 不是。
  • 为什么要这样?如果您明确没有提供 istream/ostream 来满足安全性或实时性要求怎么办?
  • @meet:“我想要一种语言中的 X”问题不受欢迎,因为答案通常只是“因为你没有想到这样做有多难”。
  • @meet 我会问你——这个“operator operator >> -- 如果我的班级有 20 名成员,而我只想输入其中的 3 名怎么办?

标签: c++ operator-overloading iostream ostream istream


【解决方案1】:

那么为什么 >> &

您列出的默认值都没有提供序列化或反序列化,这是两个非常复杂的问题,通常需要解决。

您列出的所有四件事都可以在语义上重新排序它们的操作,但是序列化/反序列化不能。

另外,序列化数据应该采用什么格式?二进制还是文本?数据字段之间应该使用什么分隔符?数据字段应该命名还是简单排序?

最后,最初的四个都不会失败,但 istream 可能有多种原因。当它失败时你会怎么做?你是返回一个部分初始化和部分默认的类还是抛出一个异常?

并不是这一系列问题无法回答,而是答案取决于你的代码的其余部分在做什么,所以不可能有一个笼统的答案。很多地方都希望能够为后者保存数据,因此紧凑的二进制表示是好的。其他地方希望能够轻松地向用户展示数据结构,这需要文本表示。

此外,到目前为止,反对该想法的最大因素是添加功能的固有成本。 This is answer on that topic(有一些关于该主题的更全面的博客文章,但我没有方便的链接,抱歉)。

【讨论】:

  • @meet:另外,还有很多 {embedded} 系统不使用流。不是每个平台都是桌面平台,而且不是每个平台都写流。此外,许多结构和类不会写入流。
猜你喜欢
  • 2022-12-06
  • 1970-01-01
  • 2018-04-19
  • 1970-01-01
  • 2022-08-14
  • 1970-01-01
  • 2014-07-30
  • 2015-12-11
  • 2014-11-24
相关资源
最近更新 更多