C++之“流”-第1课.下:实战:最简日志系统的演化

五个版本的 C++ “流”式日志系统的演化,零基础也能轻松跟进!

 1. 面向抽象编程

本课的学习重点是面向对象思想中的“向向抽象 / 接口编程,而非面向实体编程”。在C++标准库中, ostream / istream 这些抽象流(见上一节)就是抽象,对应的,具体的控制台流、内存流、文件流就是实体。

“面向抽象流” 编写日志系统,则后续课程中实现 “流式风格的日志系统”的基础。前者的学习,注重思想上的理解,后者则更多的是技巧上的学习。

2. 课堂视频

C++之“流”-第2课:最简单的流式日志系统

3. 完整代码

我们用了五个版本演进,帮助大家理解实际项目需求的常见进化,以及对应的设计改进。

3.1 版本一:手工写日志

#include <iostream>

using namespace std;

int main()
{
    cout << "【信息】:" << "即将输出你好世界!" << endl;
    cout<<"你好,世界!" << endl;
    cout << "【信息】:" << "完成输出你好世界!" << endl;
    
    cout << "【信息】:" << "终于不辱使命,即将全身而退。" << endl;
}

3.2 版本二:用上函数,减少重复

#include <iostream>
#include <string>

using namespace std;

void OutputDebugInfo(std::string const& debug_info)
{
    cout << "【信息】:" << debug_info << endl;
}

int main()
{
    OutputDebugInfo("即将输出你好世界!");
    cout<<"你好,世界!" << endl;
    
    OutputDebugInfo("完成输出你好世界!");
    OutputDebugInfo("终于不辱使命,即将全身而退。");
}

3.3 版本三:把日志写入文件!

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

void OutputDebugInfo(ofstream& ofs, std::string const& debug_info)
{
    ofs << "【信息】:" << debug_info << endl;
}

int main()
{
    ofstream ofs ("log.txt");
    
    OutputDebugInfo(ofs, "即将输出你好世界!");
    cout<<"你好,世界!" << endl;
    
    OutputDebugInfo(ofs, "完成输出你好世界!");
    OutputDebugInfo(ofs, "终于不辱使命,即将全身而退。");
}

3.4 版本四:改用抽象的流

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

void OutputDebugInfo(ostream& os, std::string const& debug_info)
{
    os << "【信息】:" << debug_info << endl;
}

int main()
{
    ofstream ofs ("log.txt");
    
    OutputDebugInfo(ofs, "即将输出你好世界!");
    cout<<"你好,世界!" << endl;
    
    OutputDebugInfo(ofs, "完成输出你好世界!");
    
    OutputDebugInfo(cout, "终于不辱使命,即将全身而退。");
}

3.5 版本五:看,这不也支持“内存流”?

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

using namespace std;

void OutputDebugInfo(ostream& os, std::string const& debug_info)
{
    os << "【信息】:" << debug_info << endl;
}

int main()
{
    ofstream ofs ("log.txt");
    
    OutputDebugInfo(ofs, "即将输出你好世界!");
    
    cout<<"你好,世界!" << endl;
    
    ostringstream oss;
    OutputDebugInfo(oss, "估计要出错了哦……");
    OutputDebugInfo(oss, "好像还真的是出错了!");
    OutputDebugInfo(oss, "原来,并没有出错啊");
    
    cout << oss.str() << endl;
    
    OutputDebugInfo(ofs, "完成输出你好世界!");
    
    OutputDebugInfo(cout, "终于不辱使命,即将全身而退。");
}

4. 课堂作业

请到 d2school.com 网站通过作业强化本课所学知识。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南郁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值