我正在实现一个类request
,它的构造函数将命令行作为其参数,并且该类将文件状态(如文件大小、上次修改时间等)作为其字段。
我想为这些字段分配值,它涉及调用fstat()
、访问 中的值struct stat
以及使用这些值。
我知道不鼓励 c++ 构造函数中的赋值,并且应该使用初始化列表,但我不知道如何在不调用构造函数主体(括号之间)和使用赋值运算符的情况下为这些字段赋值。
我该怎么办?
如果我必须在构造函数主体中初始化它们,我应该首先使用初始化所有字段NULL
(我认为这是默认完成的)吗?
class request {
vector<string> requests;
off_t content_length;
char* last_modified;
public:
explicit request(char line[]): requests(split_string(line)), content_length(NULL), last_modified(NULL) {
struct stat sb;
if(fstat(line[1], &sb) == -1) {
cerr << "Error while getting file status of the file named " << line[1] << endl;
}
content_length = sb.st_size;
last_modified = ctime(&sb.st_mtime);
}
};
这是我的代码。他们看起来好吗?