【发布时间】: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) =(赋值)运算符
那么为什么 >> & > &
【问题讨论】:
-
很少有机会流式传输类的对象状态,否则所有默认函数的概率都很高
-
对于您提到的运算符,默认行为通常很明显。
<<和>>不是。 -
为什么要这样?如果您明确没有提供 istream/ostream 来满足安全性或实时性要求怎么办?
-
@meet:“我想要一种语言中的 X”问题不受欢迎,因为答案通常只是“因为你没有想到这样做有多难”。
-
@meet 我会问你——这个“operator operator >> -- 如果我的班级有 20 名成员,而我只想输入其中的 3 名怎么办?
标签: c++ operator-overloading iostream ostream istream