1. 程式人生 > 其它 >自定義型別過載std::cout和qDebug()

自定義型別過載std::cout和qDebug()

技術標籤:# C++日常Qt日常記錄

struct ceshi
{
    int frist;
    int second;
    ceshi(int one = 0,int two = 0):frist{one},second{two}
    {
    }
    friend std::ostream& operator<<(std::ostream&,const ceshi&);
    friend QDebug operator<<(QDebug dbg, const ceshi&);
};

std::ostream & operator << (std::ostream & os,const ceshi & c)
{
    return os << "std::cout 輸出 ceshi{ frist = " << c.frist << ",second = " << c.second << "}";
}

QDebug operator<<(QDebug dbg, const ceshi & c)
{
    dbg.nospace() << "debug 輸出 ceshi{ frist = " << c.frist <<",second = "<< c.second << "}";
    return dbg;
}

#define debug qDebug()<<
int main(int argc, char *argv[])
{
    ceshi c(1,2);
    std::cout << c;
    debug c;
}

std::cout 中文亂碼......

qt有個《Custom Type Example》demo是專門介紹qDebug過載的。