运行时检查失败 #2 - 变量"l1"周围的堆栈已损坏
Run-Time Check Failure #2 - Stack around the variable 'l1' was corrupted
我目前正在测试创建一个简单的类,该类将一个数字设置为一个私有变量,遵循此链接中的最后一个解构器教程:
https://www.tutorialspoint.com/cplusplus/cpp_constructor_destructor.htm
然而,我遇到了这个特殊的问题,它说我的变量已损坏。
运行时检查失败#2-变量"l1"周围的堆栈已损坏。
此错误仅发生在Training.cpp的末尾,当它到达最后一个花括号时。
在这里,我在标题旁边定义了Line.cpp类。
//Line.cpp
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Line {
public:
void setLength(double len);
double getLength(void);
Line();
private:
double length;
};
Line::Line(void){
cout << "Object is being created." << endl;
}
void Line::setLength(double len) {
length = len;
}
double Line::getLength(void) {
return length;
}
// Line.h
#pragma once
#ifndef LINE_H
#define LINE_H
class Line
{
public:
Line();
void setLength(double len);
double getLength(void);
};
#endif LINE_H
Training.cpp调用调用Line类的主函数
// Training.cpp
#include "stdafx.h"
#include <string>
#include <iostream>
#include "Line.h"
using namespace std;
int main()
{
Line l1;
l1.setLength(10.0);
cout << "Length of line: " << l1.getLength() << endl;
return 0;
}
教程和我的版本之间唯一的区别是,我提取了类Line,并将其放在一个名为Line的类文件中,该文件由Tranining调用,其中包含主要功能。
我已经广泛搜索了这个错误的其他版本,但其中大多数都提到它似乎是某种形式超出了数组边界。然而,我没有分配任何形式的char数组,也完全不知道为什么会发生错误。你们中有谁能帮我吗?
谢谢!
您定义了两次Line类。一次在Line.h中,另一次在Line.cpp中。它们也不同(在Line.h中,它没有成员的双倍长度;)
你的Line文件应该是这样的:
//Line.cpp
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
Line::Line(void){
cout << "Object is being created." << endl;
}
void Line::setLength(double len) {
length = len;
}
double Line::getLength(void) {
return length;
}
// Line.h
#pragma once
#ifndef LINE_H
#define LINE_H
class Line
{
public:
Line();
void setLength(double len);
double getLength(void);
private:
double length;
};
#endif LINE_H
按照费德里科的回答,错误消失了。谢谢你的耐心!
只需将头文件添加到Line.cpp中,就可以了。
相关文章:
- 变量周围的堆栈'...'已损坏
- 运行时检查失败 #2 变量"A"周围的堆栈已损坏
- OpenCV代码不会检测人脸的数量,也不会在脸周围放一个圆圈
- 为什么我的 VS 代码调试器在我的C++代码周围弹跳?
- 运行时检查失败 #2 - 变量"e"周围的堆栈已损坏。发生
- 变量周围的堆栈'sortArray'已损坏
- 需要帮助编写 for 循环以在字符串周围创建边框
- 使函数参数默认为周围范围
- 变量周围的堆栈'folderPath'已损坏
- 线程构造函数周围的可变参数模板包装器无法编译
- 如何检查二维数组上的周围数字?
- 是否可以检查变量是否位于 L1/L2/L3 缓存中
- 运行时检查失败 #2 - 变量周围的堆栈'...'已损坏
- sf::Windows上的音乐:api-ms-win-crt-locale-l1-1-0.dll:无法打开共享对象文件
- 如何在屏幕周围生成随机像素
- 访问周围类中迭代器的私有值
- 运行时检查失败 #2 - 变量"l1"周围的堆栈已损坏
- C++:此代码可以编译,但引发运行时检查失败 #2 - 围绕变量周围的堆栈'num'已损坏。发生
- C 包装器C++库周围没有不必要的头文件
- OpenGL 混合会在纹理周围创建白色边框