输入、输出运算符重载???

xiaoxiao2021-03-01  11

1、>>运算符重载

ostream operator >> (ostream &o, RMB &r) // 返回引用? { o << r.x << endl; return o; // 返回ostream对象是为了与其它插入运算符连接起来, 起到一个连续输入或连续输出的效果 }

2、<<运算符重载

istream operator >> (istream &i, RMB &r) { i << r.x << endl; return i; } 3、类模板中 >> 与 << 的重载

方法一:在类模版中用友元函数重载

friend istream &operator>>(istream &in, BoundArray<T> &b) { int i; for(i = 0; i < b.n; i++) { in >> b.data[i]; } return in; }

方法二:定义全局函数,用 public 函数访问私有成员

template <class T> // 需要补加一个模板参数列表 ostream &operator<<(ostream &out, BoundArray<T> &b) { int i; for(i = 0; i < b.getn(); i++) { out << b.getdata()[i] << " "; } out << endl; return out; }
转载请注明原文地址: https://www.6miu.com/read-3350193.html

最新回复(0)