C++ 入门第 14 章 readStr 示例无法在 Visual Studio 2019 中编译

标签 c++

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 运算符变得显式。你有两个选择:

  1. 使用以前的标准编译(在 gcc 中添加标志 -std=c++98)
  2. 以这种方式明确运算符:

bool operator()(string &s) const { return !getline(is, s).fail(); }

关于C++ 入门第 14 章 readStr 示例无法在 Visual Studio 2019 中编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65014007/

相关文章:

C++使用fstream查找特定数据

c++ - 这是 "*ptr++ = *ptr + a"未定义的行为吗?

c++ - 如何在 C 代码中复制字节数组?

c++ - 处理破坏堆的对象

c++ - 了解 shared_ptr

c++ - 如何确定在给定(游戏)项目上使用定点数的可行性?

C++ 访问控制不适用于模板化对象

c++ - 婚前征服凸包算法的实现问题

C++ const 引用初始化和大括号语法

java - 使用 JNI 在 C++ 中加载 .jar 文件