c++ - 运行时检查失败 #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”周围的堆栈已损坏。发生...我在我的代码中找不到错误的地方。
解决方案
您的代码中有许多错误,都与pinakas
成员变量的性质有关。就目前而言,您将其声明为指针数组(to int
),此外,您正在使用非标准语法来表示“灵活”数组(空[]
)。
我通常不只是粘贴“固定”代码作为答案,但在这种情况下,该代码(\\\
在我进行更改的地方添加了注释)可能是帮助您的最简洁的方式。
虽然,正如这里的许多人无疑会指出的那样,最好避免使用“原始”指针和new
anddelete
运算符,而是使用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 (*)
}
随时要求任何进一步的澄清和/或解释。
推荐阅读
- npm - 重命名一个 npm 模块,对名称进行细微更改 => “包名太相似”
- python - Numpy 通过套接字串接导致解码错误
- python - Python 数据错误:ValueError:int() 的文字无效
- javascript - HTMLUnit:ReferenceError:未定义“$”
- text - Spacy TextCategorizer 使用的 CNN 可以在哪里配置?
- node.js - 在 cPanel 上托管一个不和谐的机器人
- css - 带有 :before 和 z-index 的边界半径之外的 CSS 背景
- javascript - 将xml返回到textarea php
- android-emulator - 启用 Hyper V 的系统上的 Windows Hypervisor 平台上的 Android 模拟器错误
- javascript - React js路由器更改url但不加载页面