C++ 抛出异常

标签 c++ exception

我正在学习 C++,并且花费了相当多的时间来尝试解决我遇到的错误的原因。 当我运行下面的代码时,我抛出异常。它发生在程序结束时,所以我相信它与 Edge 指针有关:

#include <iostream>
#include <vector>
#include <map>

using namespace std;


struct Edge {
    int src, dest;
};

class Graph {
    
public:
    int V, E;
    Edge *edge = new Edge[E * sizeof(Edge)];
    Graph(int Ver, int Edg);
};

Graph::Graph(int Ver, int Edg) {
    V = Ver;
    E = Edg;
}


Graph* createGraph(int V, int E) {

    Graph* graph = new Graph(V,E);
    return graph;
}

int find(int* parents, int val) {
    if (parents[val] == -1)
        return val;
    return find(parents, parents[val]);
}

void Union(int *parents, int x, int y) {
    parents[x] = y;
}


int isCycle(Graph* graph) {

    int* parents = new int[graph->V * sizeof(int)];

    memset(parents, -1, graph->V * sizeof(int));

    for (int i = 0; i < graph->E; i++) {
        int x = find(parents, graph->edge[i].src);
        int y = find(parents, graph->edge[i].dest);

        if (x == y) {
            return 1;
        };

        Union(parents, x, y);
    }


    return 0;
}



int main()
{

    int V = 9, E = 8;
    Graph* graph = createGraph(V, E);


    graph->edge[0].src = 0;
    graph->edge[0].dest = 1;

    graph->edge[6].src = 0;
    graph->edge[6].dest = 6;

    graph->edge[5].src = 0;
    graph->edge[5].dest = 7;

    graph->edge[1].src = 1;
    graph->edge[1].dest = 2;

    graph->edge[2].src = 3;
    graph->edge[2].dest = 2;

    graph->edge[3].src = 4;
    graph->edge[3].dest = 3;

    graph->edge[4].src = 4;
    graph->edge[4].dest = 5;

    graph->edge[7].src = 5;
    graph->edge[7].dest = 7;

    if (isCycle(graph))
        cout << "graph contains cycle";
    else
        cout << "graph doesn't contain cycle";

    return 0;
}

我几个月前才开始学习 C++,有人可以帮助我理解为什么我会遇到这个异常吗?

最佳答案

 Edge *edge = new Edge[E * sizeof(Edge)];

除非E被初始化,否则这会将未初始化的变量乘以sizeof(Edge)(这从表面上看也是错误的,但我们会得到稍后再说)。这是未定义的行为。

Graph::Graph(int Ver, int Edg) {
    V = Ver;
    E = Edg;
}

这还不够好。类成员的默认值(如果指定)用于在构造函数主体开始运行之前初始化它们。

执行此操作的正确方法是使用构造函数的初始化部分:

Graph::Graph(int Ver, int Edg) : V{Ver}, E{Ver}
{
}

这首先初始化 VE,所以现在:

Edge *edge = new Edge[E * sizeof(Edge)];

因此,E 现在已初始化,解决了此问题。但这仍然有点不正确。很明显,根据其余代码,这实际上应该是:

Edge *edge = new Edge[E];

在 C++ 中,当您希望声明一个包含 4 个整数的数组时,您所要做的就是声明:

int n[4];

编译器负责将 4 乘以保存 int 所需的字节数。 new 语句也是如此。如果您的目标是构造一个 #E Edge 数组,那么毫不奇怪,那就是:new Edge[E]。同样的错误在所示代码中多次出现。

关于C++ 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68793587/

相关文章:

c++ - 模板上的神秘错误

c++ - char型变量输入多个字符的效果

c++ - decltype 与具有默认参数的函数模板会产生困惑的结果(一个有趣的问题或 gcc 的错误)

javascript - JavaScript console.log/trace 等策略

exception - Grails中的JMS MessageCreator.createMessage()

c++ - 我需要 C++ 中的 UnSupportedOperationException

android - 找不到OpenCV Android C++写入

c++ - 是否有用于 Shell 扩展的点击处理程序

java - 从 @ExceptionHandler 重定向不起作用

java - HQL - 更新查询不起作用