簡體   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