1. 程式人生 > >C++ 自定義IO操作符

C++ 自定義IO操作符

C++ operator >> 與 <<

寫一個結構體,需要進行文字的讀取和輸出。需要給結構體定義操作符<<, >>。
如下是結構體的部分內容:

typedef struct __wordUnit{
    string word;
    string translation;
    __wordUnit(){
        word = "";
        translation = "";
    }
    __wordUnit(string _word, string _translation){
        word
= _word; translation = _translation; } int size(){ return word.length()+translation.length(); } bool operator ==(const __wordUnit another){ return word == another.word && translation == another.translation ; } friend __wordUnit operator +(const __wordUnit lw, const __wordUnit rw){ __wordUnit ret(lw.word
,lw.translation); ret.word = ret.word+rw.word; ret.translation = ret.translation+rw.translation; return ret; } }wordUnit;

在程式中需要將結構體內容寫入檔案中,自定義operator >>如下:

friend ofstream& operator <<(ofstream &out,__wordUnit &myWord){
    out<<myWord.word<<"\n"
; out<<myWord.translation; return out; }

相應的,輸出到stdout非常類似:

friend ostream& operator <<(ostream &out, __wordUnit &myWord){
    out<<myWord.word<<"\n";
    out<<myWord.translation;
    return out;
}

在編寫輸入操作的時候考慮到可能因為空格、換行符等特殊字元造成輸入不完整,在這個簡單的場景下直接人工處理:

friend ifstream& operator >>(ifstream &in,__wordUnit &myWord){
    in>>myWord.word;
    string str;
    in>>myWord.translation;
    while(!in.eof()){
        in>>str;
        myWord.translation += " ";
        myWord.translation += str;
    }
    return in;
}

接著,可以編寫上層檔案讀取函式:

wordUnit readWordFile(const char *path)
{
    ifstream in(path);
    if(!in.is_open()){
        LOGDBG("open failed for %s: %s", path, strerror(errno));
        return wordUnit();
    }
    wordUnit myWord;
    in>>myWord;
    in.close();
    return myWord;
}

最後,可以正常應用IO函式:

int main(int argc, char *argv[])
{
    wordUnit word1("hello","ni hao");
    wordUnit word2;
    ofstream outStream("./txt");
    outStream<<word1;
    outStream.close();

    word2 = readWordFile("./txt");
    cout<<word2;
    return 0;
}

QT 自定義QDebug輸出流

還是使用上面的結構體,不過,我們需要一點修改,將string改成QString,過載Debug流需要用到QDebugStateSaver物件儲存相關的設定。
如:

friend QDebug operator <<(QDebug debug,const __wordUnit another){
    QDebugStateSaver saver(debug);
    debug.nospace() << another.word << " " << another.translation;
    return debug;
}

最後,可以試試效果:

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    wordUnit word1("hello","ni hao");
    wordUnit word2(" word"," shi jie");
    qDebug()<<(word1 == word2);
    qDebug()<<(word1+word2);
    return a.exec();
}