首页 > 解决方案 > 运行时检查失败 #2 - 变量“e”周围的堆栈已损坏。发生了

问题描述

    #include<iostream> 
    #include <list> 
    using namespace std;

class Euler {
private:
    int korifes = 0;
    int akmes = 0;
    int* pinakas[];
public:
    void print() { cout << *pinakas[0]; return; }

    Euler(int korifess, int akmess);
    ~Euler() { delete[] *pinakas; }

    void addAkmes(int kor1, int kor2);
};

Euler::Euler(int korifess, int akmess) : akmes(akmess), korifes(korifess) {
    *pinakas = new int(korifes);
    *pinakas[0] = 89;
}

int main() {
    Euler e(2, 1);
    e.print();
}

运行时检查失败 #2 - 变量“e”周围的堆栈已损坏。发生...我在我的代码中找不到错误的地方。

标签: c++classvisual-studio-2010

解决方案


您的代码中有许多错误,都与pinakas成员变量的性质有关。就目前而言,您将其声明为指针数组(to int),此外,您正在使用非标准语法来表示“灵活”数组(空[])。

我通常不只是粘贴“固定”代码作为答案,但在这种情况下,该代码(\\\在我进行更改的地方添加了注释)可能是帮助您的最简洁的方式。

虽然,正如这里的许多人无疑会指出的那样,最好避免使用“原始”指针和newanddelete运算符,而是使用std::vector容器。

#include <iostream> 
#include <list> 
//using namespace std;/// This is considered 'bad practice' by many programmers
using std::cout;/// Just use the aspect of the STL that you need!

class Euler {
private:
    int korifes = 0;
    int akmes = 0;
    int* pinakas;/// This will point an 'array' of integers
public:
    void print() {
        cout << pinakas[0]; return;/// No longer any need for the dereference (*)
    }
    Euler(int korifess, int akmess);
    ~Euler() {
        delete[] pinakas;/// No need for the dereference (*)
    }
//  void addAkmes(int kor1, int kor2);/// You haven't provided an actual definition for this, but your never use it!
};

Euler::Euler(int korifess, int akmess) : akmes(akmess), korifes(korifess)/// NOTE: Members are initialized in DECLARATION order!
{
    pinakas = new int[korifes];/// Use "[]" (not "()") to allocate an array!
    pinakas[0] = 89;/// No need for the dereference (*)
}

随时要求任何进一步的澄清和/或解释。


推荐阅读