2013-02-01 4 views
-3

첨부 된 코드가 원하는대로 작동하는 것처럼 보입니다. 그러나 별도의 파일 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; 
} 

답변

1

나는 문제를 알아 냈습니다. 하나의 파일에서 더 작은 버전을 만들도록 압력을 가한 사람들에게 감사드립니다. 원래 프로그램에서 조작 할 객체가 여러 개 였기 때문에 main.cpp에서 함수 매개 변수로 제공된 다른 객체에서 작동하는 함수를 만들었습니다. 이렇게하면 개체의 복사본을 참조가 아닌 도우미 함수로 전달하고있었습니다. 삽입 함수가 잘 작동하는 이유는 참조로 전달했기 때문입니다. 모든 도움을 주셔서 감사 드리며,이 경험을 통해 무엇인가를 배웠다면, 최소화 된 완전한 컴파일 가능한 코드를 제공해야한다는 것이고, 앞으로 이것이 도움을받지 못하게 될 수도 있습니다.

1

하면 dataArray는 배열의 경계의 측면 값을 할당하는 부작용이 될 수보고있는 어떤 클래스의 멤버입니다.

값이 인접한 클래스 멤버에 설정되면 메모리가 프로그램에 속하기 때문에 예외가 발생하지 않습니다. 클래스는 여전히 클래스 안에 있습니다.

시나리오 :

루프가 배열을 통과하여 아무것도 찾지 않습니다.
이제 색인은 범위를 벗어났습니다.
해당 위치에있는 항목이 품목과 같은지 확인합니다. 항목과 같을 수 있습니다. 그 다음 배열의 "마지막"항목을 해당 위치에 복사합니다.

+0

기본적으로 부호없는 정수가 감소하지 않는 이유를 설명하지는 않습니다. – trumpetlicks

+0

메시지를 인쇄하는 코드를 확인 했습니까? 당신은 그것을 디버그하고 디버거와 함께 자신의 값을 볼 수 –

+0

@ YochaiTimmer 나는 그 코드를 모두 체크하고, 채워진 변화를 따르기 위해 여러 곳에서 출력을 추가했다. 어떤 이유로 그 함수는 채워진 값이 변경되지 않는다. 그것의 바깥쪽에. – cmac147

관련 문제