첨부 된 코드가 원하는대로 작동하는 것처럼 보입니다. 그러나 별도의 파일 main.cpp에있을 때 Set.h, Set.cpp filled는 remove 함수 외부에서 감소하지 않습니다. 나는 정말로 여기서 무슨 일이 벌어지고 있는지 이해하지 못한다. 또는 왜 모든 것이 하나의 파일에 모든 차이를 만들 것입니다.C++ 멤버 변수가 함수 외부에서 변경되지 않음
#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;
}
기본적으로 부호없는 정수가 감소하지 않는 이유를 설명하지는 않습니다. – trumpetlicks
메시지를 인쇄하는 코드를 확인 했습니까? 당신은 그것을 디버그하고 디버거와 함께 자신의 값을 볼 수 –
@ YochaiTimmer 나는 그 코드를 모두 체크하고, 채워진 변화를 따르기 위해 여러 곳에서 출력을 추가했다. 어떤 이유로 그 함수는 채워진 값이 변경되지 않는다. 그것의 바깥쪽에. – cmac147