C++ Primer 一书的示例代码在第 14 章中有一个名为 readStr.cpp 的示例,当我使用 cl 时它有编译错误。我在 Windows 10 上并安装了 Visual Studio 2019。我也尝试使用 g++ 进行编译并得到类似的编译错误。我也试过在我的 macbook pro 上编译它并得到类似的错误。有人可以告诉我问题的原因并提供纠正它的代码吗?本书源代码中的其他示例也会产生相同的编译错误。错误是:
readStr.cpp(32): error C2440: 'return': cannot convert from 'std::basic_istream<char,std::char_traits<char>>' to 'bool'
readStr.cpp(32): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
代码是:
#include "Version_test.h"
#include <algorithm>
using std::for_each;
#include <iostream>
using std::cin; using std::cout; using std::endl; using std::cerr;
using std::istream; using std::ostream;
#include <string>
using std::string;
#include <vector>
using std::vector;
class PrintString {
public:
PrintString(ostream &o = cout, char c = ' '):
os(o), sep(c) { }
void operator()(const string &s) const { os << s << sep; }
private:
ostream &os; // stream on which to write
char sep; // character to print after each output
};
class ReadLine {
public:
#ifdef DELETED_FCNS
ReadLine() = delete;
#endif
ReadLine(istream &i) : is(i) { }
bool operator()(string &s) const { return getline(is, s); }
private:
istream &is;
};
int main()
{
vector<string> vs;
ReadLine rl(cin); // object that read lines from cin
string s;
while (rl(s)) // store what rl reads into s
vs.push_back(s);
cout << "read : " << vs.size() << " elements" << endl;
PrintString printer; // uses the defaults; prints to cout
printer(s); // prints s followed by a space on cout
PrintString errors(cerr, '\n');
errors(s); // prints s followed by a newline on cerr
cerr << "for_each printing to cerr" << endl;
for_each(vs.begin(), vs.end(), PrintString(cerr, '\n'));
}
最佳答案
如你所见from the reference ,从 C++11 开始,bool 运算符变得显式。你有两个选择:
- 使用以前的标准编译(在 gcc 中添加标志
-std=c++98
) - 以这种方式明确运算符:
bool operator()(string &s) const { return !getline(is, s).fail(); }
关于C++ 入门第 14 章 readStr 示例无法在 Visual Studio 2019 中编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65014007/