【发布时间】:2015-10-01 01:14:24
【问题描述】:
我在将新值分配给作为 IntersectionFlowRate() 类的数据成员变量的动态 int 数组时遇到问题。我可以在构造函数中初始化并打印数组的值。但是,当我将构造函数退出到另一个类,然后在 IntersectionFlowRate() 类中调用一个函数时,传入变量以覆盖数据成员的初始值,它将出现分段错误。我已经调试发现覆盖数组会导致段错误。并且即使尝试在其函数之一中访问动态数组也会出现段错误。
我的问题是如何从动态 int 数组成员变量的一个函数中编辑其值,即 setArrayElement(int index, int x)。
这是我的一些代码。抱歉,如果我不清楚或遗漏了一些荒谬的东西。我已经坚持了好几个小时了。
#ifndef INTERSECTIONFLOWRATE_H
#define INTERSECTIONFLOWRATE_H
class IntersectionFlowRate
{
public:
IntersectionFlowRate();
~IntersectionFlowRate();
void setFlowCycle(int index, int flow);
private:
int* m_flowRateMotorCycle;
};
#endif
在.h文件中^
#include "IntersectionFlowRate.h"
#include <cstdlib>
#include <iostream>
#include <new>
using namespace std;
IntersectionFlowRate::IntersectionFlowRate()
{
const int SIZE = 4; //Constant for m_flowRates[] size
//DYNAMIC MEMORY DELETE LATER
m_flowRateMotorCycle = new int[SIZE];
for(int i = 0; i < SIZE; i++){
m_flowRateMotorCycle[i] = 0;
cout << m_flowRateMotorCycle[i] << endl;
cout << "WE GOT HERE" << endl;
}
}
void IntersectionFlowRate::setFlowCycle(int index, int flow){
cout << "INDEX: " << index << endl;
cout << "FLOW: " << flow << endl;
m_flowRateMotorCycle[index] = flow; //seg fault is here
}
我有另一个类,它创建一个指向 IntersectionFlowRate() 对象的指针,然后调用它的 setFlowCycle 函数,传入两个 VALID 整数。通过调试,我能够很好地将 0 和 3 传递给函数 setFlowCycle(0, 3) 并在函数中输出这些变量。
#ifndef TRAFFICSIM_H
#define TRAFFICSIM_H
#include "IntersectionFlowRate.h"
using namespace std;
class TrafficSim
{
public:
TrafficSim(); //Default Constructor
TrafficSim(const char* file); //Constructor
~TrafficSim(); //Destructor
private:
IntersectionFlowRate* m_flowRate;
};
#endif
#include "TrafficSim.h"
#include "IntersectionFlowRate.h"
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
TrafficSim::TrafficSim()
{
IntersectionFlowRate* m_flowRate = new IntersectionFlowRate();
m_flowRate->setFlowCycle(0, 3);
}
我用这段代码复制了错误。如果没有其他人可以,我完全不确定可能出了什么问题。
【问题讨论】:
-
您应该提供MCVE。
-
minimal 示例不是您认为问题所在的代码,它是复制问题的最小可能完整代码。我的猜测是你有一个rule of 0/3/5 违规。发布一个完整的例子。
-
A simple test 没有给我分段错误。您是否正确定义(并在需要时对其进行初始化)
m_flowRateCar? -
在现实生活中你会使用
vector<int>而不是int *,我假设你这样做是为了学习? -
我什至不知道在线 C++ IDE 的存在。下次我一定会使用它。谢谢。