Vì vậy, giả sử tôi có một vài chức năng để xử lý việc mở/đóng tệp.Không gian tên hoặc lớp, tốt hơn cho việc đóng gói chỉ các thành viên chức năng
Tốt hơn là tạo một lớp với tất cả các hàm này được khai báo tĩnh hoặc chỉ cần đặt hàm "công khai" vào tệp tiêu đề của "không gian tên" và đặt "chi tiết triển khai" còn lại trong tệp .cc?
Dưới đây là các mẫu mã.
Đó là một chút dài cho không gian tên một, vì tôi muốn làm cho nó rõ ràng nhất có thể.
THANKS !!
thi lớp
Tiêu đề:
#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 file:
/*just the implementation details of above class.*/
namespace thực hiện
Tiêu đề:
0.123.#ifndef FILE_H
#define FILE_H
#include <iostream>
#include <fstream>
#include "common.h"
namespace file {
common::Lines toLines(std::string filename);
}
#endif
.cc file:
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()
}
}
Dù bằng cách nào cũng có thể hoạt động khá tốt, nhưng không gian tên là kiểu C++ phổ biến hơn. –