c++ - 抛出异常时编译器错误

标签 c++ visual-studio-2013

我目前正在学习异常处理,这是我的部分代码:

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

相关文章:

c++ - 如何通过key从map中获取值

c++ - 符号绑定(bind)如何在 linux 中为共享库工作

C++ 函数属性指示返回值的生命周期与参数相同

azure - 使用 Visual Studio 2013 部署时未复制相关依赖项 (DLL)

javascript - Visual Studio 2013、TFS 和 _references.js 文件的问题

C++:Matrix的转置,使用SINGLE DIMENSION动态数组保存元素

c++ - 尝试使用参数包绑定(bind) std::function 时获取未声明的参数

visual-studio-2013 - xamarin 应用程序无法在 Visual Studio 2013 中部署

visual-studio-2010 - 如何从 IDE 内部运行 .bat

asp.net-mvc - FileNotFound 尝试加载 "Microsoft.VisualStudio.Web.PageInspector.Runtime"的 v14.0.0.0