2017-05-26 95 views
-2

我收到以下錯誤消息。我該如何解決它?錯誤:在vscode上使用未聲明的標識符'out_of_range'

錯誤消息

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 <stdexcept> 

如本example

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

'#include ',https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – LogicStuff

+0

謝謝。我在Vector.cpp上加了'''#include '''但它沒有工作。 – zono

+0

它在'std'命名空間中...... – LogicStuff

回答

1

嘗試,包括異常的頭。

不要忘記使用namespace std,或者使用std::來解析範圍。

+0

仍然不確定是否需要'''#包括'''。無論是否有線,它都適用於我的案例。但是,謝謝你分享,參考鏈接是非常有用的。 – zono

+1

@zono它可能會被包含在其他標準頭文件中!不用謝。 – gsamaras

相關問題