【发布时间】: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 &。 -
现在,我认为这个问题与问题不太相符,正如@acraig5075 在评论中指出的那样。 Stack Overflow 上已经有类似的问题了,所以我要删除我的问题。
【问题讨论】:
-
您无法复制流。而是存储对它的引用。将您的成员从
std::istream input_;更改为std::istream & input_; -
@JerryJeremiah 啊,对不起我的错;你是对的。我试图将代码最小化并在这里发布,我错过了使
input_成为std::istream的引用,这使得编译输出非常不同。 -
@JerryJeremiah 我修复了问题中的代码以包含最初导致编译错误的部分,这让我感到困惑。
-
问题标题与您的问题不符。