添付のコードは希望どおりに動作するようですが、別のファイルにある場合、main.cpp、Set.h、Set.cpp が塗りつぶされ、remove 関数の外でデクリメントされません。ここで何が起こっているのか本当にわかりません。または、すべてが1つのファイルにあることで違いが生じるのはなぜですか。
#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;
}