vs2017c语言未声明标识符,错误:在vscode上使用未声明的标识符'out_of_range'

本文介绍了在C++编程中遇到的一个关于Vector类的错误,涉及了`out_of_range`异常的处理。通过在Vector类的`operator[]`中添加异常处理代码,修复了程序。同时,讨论了`#include`头文件和使用`std`命名空间的重要性,并展示了如何正确地使用它们来避免编译错误。
摘要由CSDN通过智能技术生成

错误消息

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

#include

#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

#include

#include "Vector.h"

using namespace std;

2017-05-26

zono

+2

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

+0

谢谢。我在Vector.cpp上加了'''#include '''但它没有工作。 –

+0

它在'std'命名空间中...... –

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值