附加的代码似乎可以按需要工作,但是当它位于单独的文件中时,main.cpp、Set.h、Set.cpp 填充不会在删除函数之外递减。我真的不明白这里发生了什么。或者为什么它会在一个文件中产生任何影响。
#include <iostream>
using namespace std;
typedef int value_type;
class Set {
private:
value_type *dataArray, size, filled;
public:
Set() {
size = 50;
dataArray = new value_type[size];
filled = 0;
}
bool Set::isFull() const {
return (filled == size) ? true : false; // if filled is equal to size then full.
}
bool Set::remove(const value_type& item) {
for (int index = 0; index < filled; index++) {
if (index != (filled - 1) && dataArray[index] == item) {
dataArray[index] = dataArray[filled - 1];
--filled;
return true;
} else {
--filled;
return true;
}
}
return false;
}
void Set::insert(const value_type& newItem) {
if (!isFull()) {
dataArray[filled] = newItem;
filled++; // increment filled to account for new entry.
}
}
friend ostream& operator<<(ostream& out, const Set& obj) {
out << "\nfilled: " << obj.filled << endl;
out << "{";
for (int index = 0; index < obj.filled; index++) {
out << obj.dataArray[index];
if (index != (obj.filled - 1))
cout << ",";
}
out << "}";
return out;
}
};
Set firstSet;
void pauseNwait() {
cout << "<--Enter to Continue-->";
cin.ignore();
cin.get();
}
int main() {
int choice = -1;
value_type input;
while (choice != 0) {
cout << " Set Manager" << endl
<< " (1) Add item to Set 1" << endl
<< " (2) Remove item from Set 1" << endl
<< " (0) Exit" << endl
<< "-----------------------------------------" << endl
<< "Choose: ";
cin.clear();
if (cin >> choice) {
switch (choice) {
case 0:
// Exit.
break;
case 1:
cout << "Enter int to add to list: ";
cin >> input;
firstSet.insert(input);
cout << "First Set: " << firstSet << endl;
pauseNwait();
break;
case 2:
cout << firstSet << endl;
cout << "Enter item to remove from list: ";
cin >> input;
firstSet.remove(input);
cout << "First Set: " << firstSet << endl;
pauseNwait();
break;
default:
break;
}
} else {
cin.clear(); // clear cin to avoid invalid menu input errors.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
return 0;
}