c++ - c++ 方法内部的异常

标签 c++

我试图在方法中捕获异常,但我的代码无法正常工作,因为异常在调用析构函数之前关闭了程序

主要.cpp:

#include "register.h"
#include "agenda.h"
#include "professionalregister.h"
#include "personalregister.h"
#include <iostream>
#include <stdexcept>

int main(){
    Agenda agenda (2);
    Register *profissional_1 = new ProfessionalRegister ("camila", 1, 2, "engenheira", "computacao"), 
    *profissional_2 = new ProfessionalRegister ("leticia", 3, 4, "engenheira", "metalurgia"); 
    Register *pessoal =  new PersonalRegister ("Amanda" , 5, 6, "Rua", 7);
    agenda.insercao(profissional_1);
    agenda.insercao(pessoal);
    agenda.insercao(profissional_2);

    std :: cout << agenda.obter_cadastro(0)->get_nome() << std :: endl;
    std :: cout << agenda.obter_cadastro(0)->get_idade() << std :: endl;
    std :: cout << agenda.obter_cadastro(0)->get_cpf() << std :: endl;
    agenda.obter_cadastro(0)->get_atributos_extras();

    std :: cout << agenda.obter_cadastro(2)->get_nome() << std :: endl;
    std :: cout << agenda.obter_cadastro(2)->get_idade() << std :: endl;
    std :: cout << agenda.obter_cadastro(2)->get_cpf() << std :: endl;
    agenda.obter_cadastro(2)->get_atributos_extras();



    delete profissional_1;
    delete profissional_2;
    delete pessoal;
}

议程.cpp:

#include "agenda.h"
#include <stdexcept>
#include <iostream>
#include <typeinfo>

Agenda :: Agenda(int capacidade){
    _num_cad = 0;
    _cadastros.resize(capacidade);  
}

Agenda :: ~Agenda(){

}

void Agenda :: insercao(Register *inserir){
    try {
        _cadastros.at(_num_cad) = inserir;
        _num_cad++;
    }
    catch (std :: out_of_range &e){
        std :: cerr << "out_of_range" << std :: endl;
    }
}

Register* Agenda :: obter_cadastro(int posicao){
    try {
        return _cadastros.at(posicao);
    }
    catch(std :: out_of_range &e){
        std :: cout << e.waht() << std :: endl
    }
}

错误: 段错误(核心转储)

我是一名新程序员,我不知道如何解决这个问题,有人可以帮助我吗?

最佳答案

您应该开始使用调试器跟踪代码并查看执行代码时发生了什么。

但是恕我直言,您使用异常的方式是错误的。你不应该强制异常,你捕获它来打印错误。当您的函数获得不是为它设计的输入时,您应该抛出异常。例如

Register const* GetAppointment(size_t nr) const {
    if (nr < appointments.size()) {
        return appointments[nr];
    } else {
        throw std::out_of_range("Appointment number out of range.");
    }
}

请注意 std::unique_ptr 的存在,它会为您处理堆上对象的所有创建和删除。您的整个代码可能如下所示:

#include <string>
#include <sstream>

class Register{
private:
    std::string name;
    int idade, cpf;
public:
    Register(std::string_view const& name, int idade, int cpf) : name(name), idade(idade), cpf(cpf) {}
    virtual ~Register() {}
    std::string const& GetName() const { return name; }
    int GetIdade() const { return idade; }
    int GetCpf() const { return cpf; }
    virtual std::string GetExtraAttributes() const = 0;
};

class ProfessionalRegister final : public Register {
private:
    std::string function;
    std::string speciality;
public:
    ProfessionalRegister(std::string_view const& name, int idade, int cpf
        , std::string_view const& function, std::string_view const& speciality)
        : Register(name, idade, cpf)
        , function(function), speciality(speciality) {}
    std::string GetExtraAttributes() const override {
        std::stringstream out;
        out << "Function : " << function << ", Department " << speciality;
        return out.str();
    }
};

class PersonalRegister final : public Register {
private:
    std::string street;
    int number;
public:
    PersonalRegister(std::string_view const& name, int idade, int cpf
        , std::string_view const& street, int number)
        : Register(name, idade, cpf)
        , street(street), number(number) {}
    std::string GetExtraAttributes() const override {
        std::stringstream out;
        out << "Street : " << street << ", number " << number;
        return out.str();
    }
};

#include <vector>
#include <memory>
#include <iostream>
#include <stdexcept>

class Agenda {
private:
    size_t nrOfAppointments{ 0 };
    std::vector<std::unique_ptr<Register>> appointments;
public:
    Agenda(size_t capacity) : appointments(capacity) {}
    void Add(std::unique_ptr<Register>&& reg) {
        if (nrOfAppointments < appointments.size()) {
            appointments[nrOfAppointments++] = std::move(reg);
        } else {
            std::cout << "Failed adding appointment: agenda full.\n";
        }
    }
    Register const* GetAppointment(size_t nr) const {
        if (nr < appointments.size()) {
            return appointments[nr].get();
        } else {
            throw std::out_of_range("Appointment number out of range.");
        }
    }
};

int main() {
    Agenda agenda(2);
    agenda.Add(std::make_unique<ProfessionalRegister>("camila", 1, 2, "engenheira", "computacao"));
    agenda.Add(std::make_unique<ProfessionalRegister>("leticia", 3, 4, "engenheira", "metalurgia"));
    agenda.Add(std::make_unique<PersonalRegister>("Amanda", 5, 6, "Rua", 7));

    std::cout << agenda.GetAppointment(0)->GetName() << '\n';
    std::cout << agenda.GetAppointment(0)->GetIdade() << '\n';
    std::cout << agenda.GetAppointment(0)->GetCpf() << '\n';
    std::cout << agenda.GetAppointment(0)->GetExtraAttributes() << '\n';

    std::cout << agenda.GetAppointment(2)->GetName() << '\n'; // throws an exception
    std::cout << agenda.GetAppointment(2)->GetIdade() << '\n';
    std::cout << agenda.GetAppointment(2)->GetCpf() << '\n';
    std::cout << agenda.GetAppointment(2)->GetExtraAttributes() << '\n';
}

关于c++ - c++ 方法内部的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58783256/

相关文章:

c++ - 我不知道如何制作 "const unsigned float&"

c++ - 数据在调试版本中突然变为 NULL

c++ - 将 std::string 缓冲区转换为整数

c++ - 将类回调函数分配给结构?

c++ - 计算两个数字之间差异的最短方法?

c++ - Boost - 使用 TLV 编码序列化字符串

c++ - 创建一个具有两个可能继承的类

C++:没有匹配的初始化/候选构造函数不可行的构造函数:需要单个参数,但没有提供任何参数

c++ - 部分易失变量?

c++ - 寻找最短的字符串类型转换C++