【问题标题】:Initializing Constructors for istream vs file path初始化 istream 与文件路径的构造函数
【发布时间】:2022-09-23 16:27:12
【问题描述】:

我正在尝试编写一个读取文件或输入的类,但我在找出构造函数时遇到了麻烦。我想要一个读取文件名的构造函数和一个从 istream 读取的构造函数。

我不确定这是否有意义,所以如果有帮助,我会添加我的代码。

主.cc:

#include \"Doc.h\"
#include <cassert>
#include <stream>
#include <iostream>
#include <string>

using namespace std;

int main() {
    // Read from file
    Doc document(\"romeo.txt\");

    // Read from stream
    ofstream(\"data\") << \"\\r \\r  \\n\\nPeter  \\n   Ray\\r \\n  Egon  \\n \\n\\r\\n\";
    Doc d(\"data\");
    return 0;
}

文档.h:

#ifndef DOCUMENT_H
#define DOCUMENT_H

#include <iostream>
#include <string>

class Doc {
  public:
    Doc();                              // Default Constructor
    Doc(const Doc &);                   // Copy Constructor
    ~Doc();                             // Destructor
    Doc& operator=(const Doc &);        // Assignment Constructor

    // File path constructor
    Doc(std::string file_path);              // Doc(path)
    // Istream constructor
    Doc(std::istream& input);                 // Doc(istream)
}
  • 究竟是什么问题?你有那些构造函数。
  • 您拥有的 \"file path\" 和 \"istream\" 构造函数,它们有什么问题?
  • 你到底有什么问题?注意data的声明不正确
  • 顺便说一句,当您写入文件data 时,为什么要写所有这些回车符\'\\r\'?那些应该做什么?

标签: c++ class constructor


【解决方案1】:

您可以使用delegating constructor (C++11) 让文件路径构造函数调用 istream 构造函数:

Doc(const std::string& file_path)
    : Doc{std::ifstream{file_path}} // Creates an istream from the file
{}

【讨论】:

  • 好主意,不幸的是它不起作用,因为Doc(std::istream&amp;) 被引用了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-11
  • 2016-09-17
  • 2018-08-02
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多