程序停止 - 将阵列移动到函数 |C++

Program stops - move array to function | C++

本文关键字:函数 C++ 移动 阵列 程序      更新时间:2023-10-16

我有2个类。 头等舱 -Midgam- 构造函数具有以下行:

midgam = new Vector[20];

第二个类 -向量- 我在其中创建一个名为数组的数组。

该程序运行良好,只是我遇到了一个小问题。

在程序结束时,我尝试按字母顺序打印,我使用BubbleSort排序。排序工作正常,但 Swap 函数中的某些内容停止。

这是它的外观:

void Midgam::Swap(Vector *xp, Vector *yp) {
Vector temp = *xp;
cout << temp.getName() << endl;
*xp = *yp;
*yp = temp;
}
void Midgam::bubbleSort() {
int i, j;
for (i = 0; i < iterator - 1; i++) {
for (j = 0; j < iterator - i - 1; j++) {
if (midgam[j].getName().compare(midgam[j+1].getName()) > 0) {
Swap(&midgam[j], &midgam[j+1]);
}
}
}
}

我使用Visual Studio,程序停止,程序在Vector类中显示以下代码片段:

Vector::~Vector() {
if (array)
delete[] array;
}

Midgam的完整定义:

#include <iostream>
#include <string>
#include "Vector.h"
using namespace std;
#ifndef MIDGAM_H_
#define MIDGAM_H_
class Midgam {
private:
int boxNum;
int maxParties;
int iterator;
Vector *midgam;
public:
Midgam(int num_of_boxes, int num_of_parties);
virtual ~Midgam();
void Start();
void Menurmal();
void SumOfEzor();
double SumOfParty(string name);
int SumAllVotes();
void AddParty();
void Swap(Vector *xp, Vector *yp);
void bubbleSort();
void Histograma();
void PrintStars(int num);
int FindPartyByName(string party);
void PrintAll();
};
#endif /* MIDGAM_H_ */

矢量的完整定义:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#ifndef VECTOR_H_
#define VECTOR_H_
class Vector {
private:
string name;
int size;
unsigned int *array;
bool Bool;
public:
Vector(string name, int size);
Vector();
Vector & operator=(const Vector &);
virtual ~Vector();
bool StringToArray(string str);
bool getBool();
string getName();
unsigned int getAddress();
int getSize();
unsigned int getValueFromArray(int index);
double sumOfArray();
void PrintArray();
};
#endif /* VECTOR_H_ */

有谁知道为什么它不起作用?谢谢

您的Vector缺少适当的复制构造函数。

Vector temp = *xp;
//NOT EQUAL TO:
//Vector temp;
//temp=*xp;

即使有等号,上面的语句也不会调用operator=(const Vector &)。以下行是正确的和等效的:

Vector temp(*xp);

原因是这是一个副本初始化-temp已创建,因此必须调用构造函数 - 特别是复制构造函数Vector(const Vector &)。您没有明确声明,因此使用了默认的。

然后创建一个浅拷贝,temp*xp然后共享同一个数组,当它们的析构函数都被调用时,第二个析构函数将尝试删除已删除的内存 - 未定义的行为会触发Visual Studio的调试器(至少在调试模式下)。

解决方案是执行适当的深度复制 - 创建一个新数组并复制其内容:

#include <algorithm> #Contains std::copy_n
Vector::Vector(const Vector& other)
{
name=other.name;
size=other.size;
//Creates a new array
array= new unsigned int[size];
//Copies the array contents
std::copy_n(other.array,size,array);
Boo=other.Bool;
}

这也是为什么不使用原始内存的一个主要示例。我知道您正在实现自定义向量,并且不想将std::vector用于array但至少使用std::unique_ptr.如果你只是这样做,你就不必首先问这个问题,因为编译器会抱怨,调试器也不必做编译器的工作。