IO对象不可以复制或者赋值
生活随笔
收集整理的這篇文章主要介紹了
IO对象不可以复制或者赋值
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
標(biāo)準(zhǔn)庫類型不允許復(fù)制或者賦值操作;
ofstream out1,out2;
out1=out2;//error
由兩層特別重要的含義:
(1)只有支持復(fù)制的元素類型可以存儲(chǔ)在vector或者其他容器類型中。由于流對象不能復(fù)制,因此不可以存儲(chǔ)在vector或者其他的容器中;
(2)形參或者返回類型不能為流類型,如果需要傳遞或者返回IO對象,則必須傳遞或者返回指向該對象的指針或者引用。
對IO對象的讀寫會(huì)改變流對象的狀態(tài),因此引用必須是非const類型;
下面的代碼為何沒有輸出???
#include <iostream> #include <string> #include <fstream> #include <sstream> using namespace std; int main() {std::ofstream out1,out2;out1 << "Today is saturday@!!!" << endl;out2 << "You are very good!!!" << endl;int i =2;out1 << i << endl;return 0; }下面用指針傳遞流對象:
#include <iostream> #include <string> #include <fstream> #include <sstream> using namespace std; ostream * print(ostream *os); int main() {print(&cout);out1 << i << endl;return 0; } //if you will return or pass or return a stream object ,you will use //references or pointer ostream * print(ostream * os) {(*os) << "This is a ostream object!!!" << endl;return os; }總結(jié):傳遞流對象可以使用指針。和普通指針一樣使用方法!
總結(jié)
以上是生活随笔為你收集整理的IO对象不可以复制或者赋值的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于c++静态成员函数
- 下一篇: 如何检测ARP病毒,arp病毒怎么解决?