Re: [問題] 關於operator
※ 引述《tyc5116 (累人啊....)》之銘言:
: to h大,對於您寫的這些有些不是很懂,我的結構中,指的是aaa物件中會含有多個a物件
: 不過aaa中不只有list<a> v這個物件而已,不好意思,這裡沒補到
: 所以一般的list結構,我是用這樣的方式在記錄的
: void aaa::RecordData(string* path){
: ofstream outfile((*path).c_str(),ios::out);
: if (!outfile)
: System::Windows::Forms::MessageBox::Show("開啟失敗");
: for (list<TPGra>::iterator i=Load.begin();i!=Load.end();++i){
: outfile <<*i ;
: }
如果你要直接在這裡把list寫出去 就不需要我上面四個函數中的後兩個了
ostream& operator<<(ostream& out,aaa& v);
這個的目的是對Type aaa重載 <<運算子
如果你有重載operator<<
這三行for迴圈就能改寫成一行 outfile << *this;
: outfile.close();
: outfile.clear();
: }
: 像這樣,以迴圈紀錄,ostream的部份就這樣寫
: ostream& operator<<(ostream& out,a& va){
: return out << v.GetID() << " " << vTPData.GetName()<<endl;
: ^^^^^^^^^ ^^^^^^^^^物件a的屬性
: }
: istream& operator<<(istream& in,TPData& vTPData){
: return in >> vTPData.GetID() >> vTPData.GetName();
: }
注意這兩個函式是要宣告在class a(或vTPData)的friend,而不是aaa的friend
因為你的目的是要存取a(或vTPData)的private
: 但因為目前的aaa有vector的屬性,所以我寫成這樣(以ostream為例)
: return out << va.GetID() << " "
: << va.GetName() << " "
: << va.v << " ";
: 很明顯,這個會錯,不過就是這個部份不會改
兩種方法
1.像上面處理list一樣,用一個迴圈輸出vector內所有的元素
2.overload std::vector<>的operator <<
注意,C++標準不允許你改變/添加namespace std裡的東西
所以你重載的函式要放在自己的namespace或global namespace
: 針對您的4個friend宣告,我不了解的是他第二個參數該怎麼宣告
: (跟我原來的有些不同),剩下的實作我應該看的懂(應該吧....@@)
你原本關於a的那兩個(前兩個)宣告錯位置了
關於aaa的那兩個(後兩個) 前面有說明
如果你打算在LoadContent裡面處理 就不用重載 aaa的 operator <<
: 然後對於Boost::serialization,我有去看了,但我練習的時候
: include抓不到,是安裝後將boost資料夾放到專案裡面嗎?
在你的IDE(VC, DevC, etc..)的include資料夾設定裡面加入含有boost資料夾的那個目錄
不用把整個boost的include檔都copy到專案裡..
指定位置讓compiler自己去找就好
注意要指定搜尋的是boost的父目錄 而不是boost這個目錄
#include <boost/xxxxxxxx.h>像這樣使用
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.32.15.163
※ 編輯: holymars 來自: 114.32.15.163 (09/15 17:10)
討論串 (同標題文章)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章