[英]Compiler error when throwing exception
I am currently learning about exceptions handling, and here is part of my code: 我目前正在学习有关异常处理的知识,这是我的代码的一部分:
//vector.cpp
#include "vector.h"
Vector::Vector(int s)
{
if (s < 0) throw length_error{};
elem = new double[s];
sz = s;
}
here is the code I am trying to test the exception by: 这是我试图通过以下方式测试异常的代码:
try{
Vector v(-27);
}
catch (length_error)
{
cout << "There was a negative size for your vector.\n";
}
catch (bad_alloc)
{
cout << "The memory was not allocated properly.\n";
}
When I try to run my application, I get the following error: 当我尝试运行我的应用程序时,出现以下错误:
error C2440: '<function-style-cast>' : cannot convert from 'initializer-list' to 'std::length_error'
Where is the error? 错误在哪里?
EDIT: The code was copied from C++ Programming Language Book . 编辑:代码是从C ++编程语言Book中复制的。
According to cppreference.com std::length_error
has the two constructors: 根据cppreference.com, std::length_error
具有两个构造函数:
explicit length_error( const std::string& what_arg );
explicit length_error( const char* what_arg );
And you are trying to construct with an empty parameters list. 而且您正在尝试使用空的参数列表进行构造。 You need to pass in a string to the constructor. 您需要将字符串传递给构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.