运行时检查失败 #2 - 变量"l1"周围的堆栈已损坏

Run-Time Check Failure #2 - Stack around the variable 'l1' was corrupted

本文关键字:l1 周围 堆栈 已损坏 变量 检查 失败 运行时      更新时间:2023-10-16

我目前正在测试创建一个简单的类,该类将一个数字设置为一个私有变量,遵循此链接中的最后一个解构器教程:

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中,就可以了。