【问题标题】:How to pass std::cin to a class constructor?如何将 std::cin 传递给类构造函数?
【发布时间】:2021-08-27 03:19:10
【问题描述】:

我正在尝试创建一个可以从文件流或std::cin 读取输入的类:

#include <string>
#include <iostream>
#include <mutex>

class A
{
public:
  explicit A(std::istream& input)
    : input_(input)
  {
    ;
  }

public:
  void doSomething()
  {
    std::string word;
    while (input_ >> word) {
      std::cout << word << std::endl;
    }
  }

private:
  std::istream& input_;

  std::mutex mutex_;
};

int main()
{
  auto a = A(std::cin);
  a.doSomething();
  return 0;
}

但编译器给出以下输出:

~/test/main.cpp: In function ‘int main()’:
~/test/main.cpp:31:22: error: use of deleted function ‘A::A(A&&)’
   auto a = A(std::cin);
                      ^
~/test/main.cpp:5:7: note: ‘A::A(A&&)’ is implicitly deleted because the default definition would be ill-formed:
 class A
       ^
~/test/main.cpp:5:7: error: use of deleted function ‘std::mutex::mutex(const std::mutex&)’
In file included from /usr/include/c++/7/mutex:43:0,
                 from ~/test/main.cpp:3:
/usr/include/c++/7/bits/std_mutex.h:97:5: note: declared here
     mutex(const mutex&) = delete;
     ^~~~~

我应该如何修复错误?或者一般来说,我们如何创建一个可以从文件流或std::cin 读取输入的类?


编辑

  • 最初我尝试尽可能减少代码量,在此过程中,我删除了std::mutex 部分,这给出了非常不同的编译器输出。另外,有一个错字,input_ 是 std::stream,@JerryJeremiah 在第一条评论中是正确的,应该是 std::istream &amp;。

  • 现在,我认为这个问题与问题不太相符,正如@acraig5075 在评论中指出的那样。 Stack Overflow 上已经有类似的问题了,所以我要删除我的问题。

【问题讨论】:

  • 您无法复制流。而是存储对它的引用。将您的成员从 std::istream input_; 更改为 std::istream &amp; input_;
  • @JerryJeremiah 啊,对不起我的错;你是对的。我试图将代码最小化并在这里发布,我错过了使input_成为std::istream的引用,这使得编译输出非常不同。
  • @JerryJeremiah 我修复了问题中的代码以包含最初导致编译错误的部分,这让我感到困惑。
  • 问题标题与您的问题不符。

标签: c++ c++11 cin istream


【解决方案1】:

我找到了答案。

std::mutex 不可复制,包含它的类也不可复制。

代码应该是:

int main()
{
  A a(std::cin);
  a.doSomething();
  return 0;
}

【讨论】:

  • 干得好,推动并找到答案。
猜你喜欢
  • 2012-08-13
  • 1970-01-01
  • 1970-01-01
  • 2018-06-24
  • 2015-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多