ostream operator<< (ostream &os, R &r) {
os << r.n << ',' << r.d;
return os; // 報錯
}
錯誤原因:
ostream&(引用),而非 ostream(值拷貝)。ostream 禁止拷貝構造R &r 應為 const R &r,因輸出操作不應修改對象operator<< 通常需聲明為 友元函數 以訪問私有成員class Test {
public:
int a, b;
Test() : a(0), b(0) {}
Test(int a, int b) : a(a), b(b) {}
// 友元函數聲明(類內部)
friend ostream& operator<<(ostream& os, const Test& t);
friend istream& operator>>(istream& is, Test& t);
};
// 類外部實現
ostream& operator<<(ostream& os, const Test& t) {
os << "a = " << t.a << endl;
os << "b = " << t.b << endl;
return os; // 返回引用,支持鏈式調用
}
istream& operator>>(istream& is, Test& t) {
is >> t.a >> t.b;
return is;
}
| 項目 | 正確寫法 | 說明 |
|---|---|---|
| 返回類型 | ostream& | 流對象不可拷貝,必須返回引用 |
| 第一參數 | ostream& os | 流對象引用 |
| 第二參數 | const T& obj | 常引用,保證只讀 |
| 訪問私有成員 | 聲明 friend | 非成員函數訪問私有數據必須友元 |
| 鏈式調用 | return os; | 支持 cout << a << b; |
class R {
public:
int n, d;
R(int a, int b) : n(a), d(b) {}
friend ostream& operator<<(ostream& os, const R& r);
};
ostream& operator<<(ostream& os, const R& r) {
os << r.n << ',' << r.d;
return os;
}
int main() {
R a(2,3), b(4,5);
cout << a << b; // 輸出: 2,34,5
return 0;
}
iomanip 控制寬度、精度等operator>> 同理,第二參數為非 const 引用(需修改對象)