Visual Studio - 使用自定义C++头文件时出现编译时错误 - "std_lib_facilities.h"

visual studio - Compile-time error while using custom C++ header file - "std_lib_facilities.h"

本文关键字:std 编译时错误 lib facilities Studio 自定义 C++ 文件 Visual      更新时间:2023-10-16

我是C++的新手,我正在学习这本书——编程原理和;Bjarne Stroustrup的《使用C++练习》,第1版。作者在每个程序中都使用一个头文件std_lib_facilities.h(此处(——示例、演练或练习。

我正试图解决第4章中的问题13——

创建一个程序来查找1到100之间的所有素数。有一种经典的方法可以做到这一点,称为"筛埃拉托斯梯尼。"你不知道这个方法,上网看看把它挂起来。用这种方法编写程序。

当我试图编译我的程序时(我使用的是Visual Studio 2013(,这里-

// Sieve of Eratosthenes
#include "std_lib_facilities.h"
int main()
{
    int max = 100, i = 0, j = 0, total = 0;
    vector<bool> primes(max + 1, true);
    // Find primes using Sieve of Eratosthenes method
    primes[0] = false;
    primes[1] = false;
    for (i = 0; i <= max; ++i){
        if (primes[i] == true){
            for (j = 2; i * j <= max; ++j){
                primes[i * j] = false;
            }
        }
    }
    // Show primes
    cout << "nnAll prime numbers from 1 to " << max << " -nn";
    for (i = 0; i < primes.size(); ++i)
        if (primes[i] == true){
            cout << i << " ";
            ++total;
        }
    cout << "nnTotal number of prime numbers == " << total << "nn";
    keep_window_open();
    return 0;
}

它显示了这个我无法理解的错误-

1>  13_4exercise.cpp
1>c:usersi$hudocumentsvisual studio 2013projectsc++ developmentc++ development13_4exercise.cpp(23): warning C4018: '<' : signed/unsigned mismatch
1>c:usersi$hudocumentsvisual studio 2013projectsc++ developmentc++ developmentstd_lib_facilities.h(88): error C2440: 'return' : cannot convert from 'std::_Vb_reference<std::_Wrap_alloc<std::allocator<char32_t>>>' to 'bool &'
1>          c:usersi$hudocumentsvisual studio 2013projectsc++ developmentc++ developmentstd_lib_facilities.h(86) : while compiling class template member function 'bool &Vector<bool>::operator [](unsigned int)'
1>          c:usersi$hudocumentsvisual studio 2013projectsc++ developmentc++ development13_4exercise.cpp(11) : see reference to function template instantiation 'bool &Vector<bool>::operator [](unsigned int)' being compiled
1>          c:usersi$hudocumentsvisual studio 2013projectsc++ developmentc++ development13_4exercise.cpp(8) : see reference to class template instantiation 'Vector<bool>' being compiled

这个错误意味着什么?如何解决这个问题?

您的库"std_lib_facilities.h"正在使用vector的自定义实现,该实现没有vector<bool>专用模板。

专用模板使用allocator<bool>vector<bool>::reference作为operator[]的返回值。

在您的情况下,它使用的是默认分配器,它从operator[]返回std::_Vb_reference<std::_Wrap_alloc<std::allocator<char32_t>>>——因此您的问题出现了。

这个问题与您的头有关。

如果您将此include替换为纯标准标头,它将进行编译:

#include <iostream>
#include <vector>
using namespace std;  // for learning purpose

并用CCD_ 11 替换CCD_