天天看点

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      

在程序中需要将结构体内容写入文件中,自定义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      

最后,可以正常应用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输出流

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();
}