2014-03-06 2 views
1

저는 4 문자열, 4 int 및 벡터 (int)를 마지막 인수로 사용하여 Client 클래스를 만들어야하는 학교에서 일하고 있습니다. 문제는, 모든 벡터의 요소를 인쇄하려고 할 때, 내가 직접 mutator를 사용한다면, 그것이 인쇄되고 있다는 것입니다.C++ 이상한 행동 뮤 테이타 벡터

vector<int> v_int; 
vector<int>::iterator it_v_i; 
v_int.push_back(2); 
v_int.push_back(3); 
v_int.push_back(7); 
v_int.push_back(1); 

Client client("nom1", "prenom1", "adress1", "city1", "comment1", 1240967102, 44522, 5, 10, v_int); 

v_int = client.getIdResources(); 
for (it_v_i = v_int.begin(); it_v_i != v_int.end(); it_v_i++) { 
    cout << *it_v_i << ", "; 
} 

예상대로 인쇄 2,3,7,1하지만 다음 코드

for (it_v_i = client.getIdResources().begin(); it_v_i != client.getIdResources().end(); it_v_i++) { 
    cout << *it_v_i << ", "; 
} 

인쇄 미확인 번호 (3417664 등 ...), 미확인 번호 7, 1

난 정말 이런 일이 왜 이해하지

편집 :

,691 363,210

생성자 :

Client::Client(const string& name, const string& surname, const string& adress, const string& city, const string& comment, 
      const int& phoneNb, const int& postalCode, const int& termAppointment, const int& priority, const vector<int>& idResources) 
       : name(name), surname(surname), adress(adress), city(city), comment(comment), phoneNumber(phoneNb), 
       postalCode(postalCode), termAppointment(termAppointment), priority(priority), idResources(idResources) 

{ }

은 테이터 :

std::vector<int> getIdResources() const{ return idResources; } 

답변

3

문제는 두 번째 코드에서 임시 vector S는 begin()end() 반복자를 얻기 위해 사용되는 것입니다 (선언문이 std::vector<int> client.getIdResources()이고 std::vector<int>& client.getIdResources()이 아님). 즉, it_v_i은 소멸 된 요소 인 std::vector을 나타냅니다. it_v_i이 참조 해제되면 정의되지 않은 동작이 발생합니다.

두 번째 코드 단편을 올바르게 작동 시키려면 std::vector에 대한 참조를 client.getIdResources()으로 반환해야합니다. 그러나 내부 클래스 멤버에 대한 참조를 반환하면 평생 문제와 같은 다른 문제가 발생합니다.

+0

이렇게하면 첫 번째 사례 만 제대로 수행 할 수있는 유일한 방법입니다. –

+0

@DadEapPurple, yes 또는'get std :: vector &'를 반환하도록'getIdResources()'를 수정하십시오. – hmjd