所以说,我有几个功能来处理文件的打开/关闭.
最好使一个类静态地声明所有这些功能
或者简单地将“public”函数放在命名空间“file”的头文件中,并将其他“实现细节”放在.cc文件中?
以下是代码示例.
对于命名空间来说,这是一个很长的时间,因为我想尽可能的清楚.
谢谢!!
课程实施
标题:
#ifndef FILE_H #define FILE_H #include <iostream> #include <fstream> include "common.h" enum Errorcode { FILE_CANNOT_OPEN,FILE_CANNOT_CLOSE }; class file { public: static common::Lines toLines(std::string filename); private: static void err(Errorcode e,std::string msg); static void toLines(std::ifstream &ifs,common::Lines &lines); }; #endif
.cc文件:
/*just the implementation details of above class.*/
命名空间实现
标题:
#ifndef FILE_H #define FILE_H #include <iostream> #include <fstream> #include "common.h" namespace file { common::Lines toLines(std::string filename); } #endif
.cc文件:
namespace file { enum Errorcode { FILE_CANNOT_OPEN,FILE_CANNOT_CLOSE }; void err(Errorcode e,std::string msg); void toLines(std::ifstream& ifs,common::Lines &lines); common::Lines toLines(std::string filename) { std::vector<std::string> lines; try { std::ifstream ifs(filename.c_str()); if (ifs.fail()) throw FILE_CANNOT_OPEN; toLines(ifs,lines); ifs.close(); if (ifs.fail()) throw FILE_CANNOT_CLOSE; } catch (Errorcode e) { err(e,filename); } return lines; } void err(Errorcode e,std::string msg) { switch (e) { default: std::cerr << "Unknown error.\n"; break; case FILE_CANNOT_OPEN: std::cerr << "file \"" << msg << "\" could not be opened.\n"; break; case FILE_CANNOT_CLOSE: std::cerr << "file \"" << msg << "\" could not be closed.\n"; break; } std::exit(-1); } void toLines(std::ifstream& ifs,common::Lines &lines) { std::string line; while(std::getline(ifs,line)) { lines.push_back(line); } ifs.clear(); // clear error bit set by getline() } }