c – 命名空间或类,它只适用于封装功能成员
发布时间:2020-12-16 03:37:48 所属栏目:百科 来源:网络整理
导读:所以说,我有几个功能来处理文件的打开/关闭. 最好使一个类静态地声明所有这些功能 或者简单地将“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() } } 解决方法
表面上,静态类函数和命名空间函数几乎是相同的,事实上,在名字空间支持普及之前的早期阶段就使用了类.
如今,您应该最能表达程序的逻辑结构(即心理模型).如果您正在对相关函数进行分组,那么它是一个命名空间. 然而,技术上的差异在于命名空间参与参数相关查找(ADL),而类成员函数不能,但是类可以转换为模板和专门的.如果任何这些语义差异对您很重要,那么这个考虑可能会帮助您做出正确的选择. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |