You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

《C++之旅》第二版中Negative_size异常编译报错求解

问题解决:《C++之旅》第二版第80页Negative_size异常编译错误

问题核心

代码里的Negative_size并非C++标准库中的异常类型,所以加std::前缀会触发编译错误——它是作者为示例场景自定义的异常类,书中为了聚焦模板语法,省略了异常类的定义部分。

两种可行解决方式

1. 补全自定义Negative_size异常类

继承标准异常类(如std::invalid_argument),让它能兼容C++标准异常处理流程:

#include <stdexcept>  // 必须包含标准异常头文件

// 自定义Negative_size异常类
class Negative_size : public std::invalid_argument {
public:
    // 构造函数,传入默认错误提示
    Negative_size() : std::invalid_argument("Vector size cannot be negative") {}
};

然后修改Vector构造函数中的throw语句,去掉std::前缀:

template <typename T>
Vector<T>::Vector(int s)
{
    if (s < 0) {
        throw Negative_size{};  // 直接抛出自定义异常
    }
    // 补充原书中省略的初始化逻辑
    sz = s;
    elem = new T[s];
}

2. 替换为标准库内置异常

如果不想自定义异常,直接使用C++标准库提供的std::invalid_argument更符合标准实践,也省去自定义类的麻烦:

#include <stdexcept>

template <typename T>
Vector<T>::Vector(int s)
{
    if (s < 0) {
        throw std::invalid_argument("Vector size cannot be negative");
    }
    // 补充初始化逻辑
    sz = s;
    elem = new T[s];
}

补充说明

书中这段示例优先展示模板类的核心结构,简化了异常相关的细节,勘误表未收录这个疏漏。实际编码时,要么补全自定义异常的定义,要么直接复用标准库异常类型即可解决问题。

内容的提问来源于stack exchange,提问作者heretoinfinity

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 10:52:35