【问题标题】:error: use of undeclared identifier 'out_of_range' on vscode错误:在 vscode 上使用未声明的标识符“out_of_range”
【发布时间】:2017-05-26 11:10:51
【问题描述】:

我收到以下错误。我该如何解决?

错误信息

Vector.cpp:9:49: error: expected ';' after expression
if (i < 0 || size() <= i) throw out_of_range{"Vector::operator[]"};
                                            ^
                                            ;
Vector.cpp:9:37: error: use of undeclared identifier 'out_of_range'
if (i < 0 || size() <= i) throw out_of_range{"Vector::operator[]"};
                                ^
Vector.cpp:9:70: error: expected ';' after expression
if (i < 0 || size() <= i) throw out_of_range{"Vector::operator[]"};

user.cpp

#include <iostream>
#include <cmath>

#include "Vector.h"

using namespace std;

double sqrt_sum(Vector& v)
{
    double sum = 0;
    for (int i = 0; i != v.size(); ++i)
        sum += sqrt(v[i]);
    return sum;
}

int main() {
    Vector v(1);
    int sum = sqrt_sum(v);
    cout << sum << endl;
}

Vector.h

class Vector
{
    public:
        Vector(int s);
        double& operator[](int i);
        int size();
    private:
        double* elem;
        int sz;
};

Vector.cpp

#include "Vector.h"

Vector::Vector(int s):elem {new double[s]}, sz{s} 
{
}

double& Vector::operator[](int i)
{
    if (i < 0 || size() <= i) throw out_of_range{"Vector::operator[]"}; // it works when this line is commented out
    return elem[i];
}

int Vector::size()
{
    return sz;
}

tasks.json

{
    "version": "0.1.0",
    "command": "g++",
    "isShellCommand": true,
    "args": ["-std=c++11", "-O2", "-g", "user.cpp", "Vector.cpp"],
    "showOutput": "always"
}

更新 1

我添加了以下两行,然后就可以了。

#include <iostream>
#include "Vector.h"
using namespace std;

【问题讨论】:

  • #include &lt;stdexcept&gt;, stackoverflow.com/questions/1452721/…
  • 谢谢。我在 Vector.cpp 顶部添加了#include &lt;stdexcept&gt;,但它不起作用。
  • 它在std命名空间...
  • @LogicStuff 谢谢!

标签: c++ visual-studio-code


【解决方案1】:

尝试包含异常的标头:

#include <stdexcept>

example所示。

别忘了使用命名空间std,或者用std::解析范围。

【讨论】:

  • 仍然不确定是否需要#include &lt;stdexcept&gt;。无论有没有这条线,它都适用于我的情况。但谢谢你分享这点,参考链接非常有用。
  • @zono 它可能会包含在其他一些标准标题中!不客气。
猜你喜欢
  • 1970-01-01
  • 2013-03-12
  • 2014-08-04
  • 2020-05-05
  • 2019-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多