我目前正在学习异常处理,这是我的部分代码:
//vector.cpp
#include "vector.h"
Vector::Vector(int s)
{
if (s < 0) throw length_error{};
elem = new double[s];
sz = s;
}
这是我试图通过以下方式测试异常的代码:
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";
}
当我尝试运行我的应用程序时,出现以下错误:
error C2440: '<function-style-cast>' : cannot convert from 'initializer-list' to 'std::length_error'
哪里出错了?
编辑:代码复制自 C++ Programming Language Book .
最佳答案
根据 cppreference.com std::length_error
有两个构造函数:
explicit length_error( const std::string& what_arg );
explicit length_error( const char* what_arg );
并且您正在尝试使用空参数列表进行构造。您需要将一个字符串传递给构造函数。
关于c++ - 抛出异常时编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18054135/