我在分配某些代码时遇到麻烦。该程序基于面向大学生的在线竞赛问题存档。
这是头文件:
#include <iostream>
#include <cmath>
using namespace std;
class Vito
{
public:
Vito(int relative_count); //constructor
~Vito(); //destructor
int min(); //finds minimum "distance" between vito's relatives
private:
int *streets; //pointer to array of street numbers
int sum(int index); //generates sum of distances for each of vito's relatives
void getStreetNums(); //retrieves street numbers from user
int relatives; //used globaly to set number of repititions
};
Vito::Vito(int relative_count = 0)
{
int *streets = new int[relative_count]; //allocates memory for array streets
relatives = relative_count;
getStreetNums();
}
Vito::~Vito()
{ delete [] streets; } //releases memory used by class
void Vito::getStreetNums()
{
cout << "Enter all street numbers, seperated by a space: ";
int street_num;
for (int i = 0; i < relatives; i++)
{
cin >> street_num;
streets[i] = street_num;
}
}
int Vito::min()
{
int MIN = 65546, test_distance; //initialized to maximum possible value for an integer in C++
for (int i = 0; i < relatives; i++)
{
test_distance = sum(i);
if( MIN > test_distance )
{ MIN = test_distance; }
}
return MIN;
}
int Vito::sum(int index)
{
int SUM = 0, street_num;
street_num = *(streets+index); //set value for determining distances between one house and the others
for (int i = 0; i < relatives; i++)
{ SUM += abs( street_num - streets[i] ); }
return SUM;
}
这是主要的:
#include <iostream>
#include "proj_02.h"
using namespace std;
int main()
{
int relatives, tests;
cout << "This program will supply a minimum distance between homes based on a given number of relatives and street numbers their homes are on. All entered values must be integers." << endl << endl;
cout << "Enter how many tests will be run: ";
cin >> tests;
for (int i = 0; i < tests; i++)
{
cout << "Enter how many relatives will be used in test " << i+1 << ": ";
cin >> relatives;
Vito family(relatives);
cout << "For this case, the minimum distance between each relatives house compared to each other is: " << family.min() << endl << endl;
}
}
执行后,我收到一条错误消息,内容为“ 0xC0000005:访问冲突写入位置0x00000000”。这里:
void Vito::getStreetNums()
{
cout << "Enter all street numbers, seperated by a space: ";
int street_num;
for (int i = 0; i < relatives; i++)
{
cin >> street_num;
streets[i] = street_num;
}
}
调试显示为街道设置了空的内存地址,但是我在构造函数中为它分配了内存。谁能解释这是怎么回事?
最佳答案
Vito::Vito(int relative_count = 0)
{
int *streets = new int[relative_count]; //allocates memory for array streets
在构造函数中,您定义了局部变量
streets
,并为其分配内存。局部变量streets
遮盖了类成员streets
。更改为:Vito::Vito(int relative_count = 0)
{
streets = new int[relative_count]; //allocates memory for array streets