【发布时间】:2021-11-17 07:55:03
【问题描述】:
错误出现在第 76 行 int res[mSize];,问题出现在 mSize。这似乎是一个简单的修复,但我无法弄清楚。如果有人能弄清楚或指出我正确的方向,将不胜感激。
还有,解构器~MyContainer(),我不知道我用对了还是有合适的地方放。
这是我的代码:
#include <iostream>
using namespace std;
class MyContainer
{
private:
int* mHead; // head of the member array
int mSize; // size of the member array
public:
MyContainer();
MyContainer(int*, int);
//~MyContainer();
void Add(int);
void Delete(int);
int GetSize();
void DisplayAll();
int FindMissing();
~MyContainer() {}
};
MyContainer::MyContainer()
{
mHead = NULL;
mSize = 0;
}
MyContainer::MyContainer(int* a, int b)
{
mHead = a;
mSize = b;
}
void MyContainer::Add(int a)
{
*(mHead + mSize) = a;
mSize++;
}
void MyContainer::Delete(int a)
{
int index;
for (int i = 0; i < mSize; i++)
{
if (*(mHead + i) == a)
{
index = i;
break;
}
}
for (int i = index; i < mSize; i++)
{
*(mHead + i) = *(mHead + i + 1);
}
mSize--;
}
int MyContainer::GetSize()
{
return mSize;
}
void MyContainer::DisplayAll()
{
cout << "\n";
for (int i = 0; i < mSize; i++)
{
cout << *(mHead + i) << " ";
}
}
int MyContainer::FindMissing()
{
int res[mSize];
int temp;
int flag = 0;
for (int i = 1; i <= mSize; i++)
{
flag = 0;
for (int j = 0; j < mSize; j++)
{
if (*(mHead + j) == i)
{
flag = 1;
break;
}
}
if (flag == 0)
{
temp = i;
break;
}
}
return temp;
}
int main()
{
const int cSize = 5;
int lArray[cSize] = { 2, 3, 7, 6, 8 };
MyContainer lContainer(lArray, cSize);
lContainer.DisplayAll();
lContainer.Delete(7);
lContainer.DisplayAll();
cout << "Size now is: " << lContainer.GetSize() << endl; lContainer.Add(-1);
lContainer.Add(-10);
lContainer.Add(15);
lContainer.DisplayAll();
cout << "Size now is: " << lContainer.GetSize() << endl;
cout << "First missing positive is: " << lContainer.FindMissing() << endl;
system("PAUSE"); return 0;
}
【问题讨论】:
-
数组需要有一个恒定的大小,所以你不能在运行时选择大小。使用
std::vector将解决该问题。 -
在
MyContainer::MyContainer(int* a, int b)中,ownsa指向的分配是谁?在开始使用析构函数之前,这是一件非常重要的事情。如果您决定需要一个析构函数,那么您需要阅读有关 the Rule of Three 和朋友的信息。 -
更密切相关,
int res[mSize];是什么?它似乎没有使用,我想不出我会用它做什么。您不能返回一个作为局部变量的数组,它 decays to a pointer 然后超出范围,给调用者留下一个定时炸弹,因此您甚至不能使用它来跟踪多个丢失的数字。 -
'
this' 和它有什么关系?你对析构函数有什么疑问?