繁体   English   中英

引发异常时的编译器错误

[英]Compiler error when throwing exception

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

//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 ++编程语言Book中复制的。

根据cppreference.com, std::length_error具有两个构造函数:

explicit length_error( const std::string& what_arg );
explicit length_error( const char* what_arg );

而且您正在尝试使用空的参数列表进行构造。 您需要将字符串传递给构造函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM