2014-09-10 1 views
-1

이것은 아마도 대부분의 기본적인 질문처럼 보일 것입니다.유형이 <Object*>이고 이동하는 벡터

클래스를 aTask라고합니다.

Class aTask{ 


    string taskID; 
    int taskDuration; 
    std::vector<aTask*> taskList; 

    //copy constructor and such 

    aTask(const string& id, int duration){ 
     taskDuraion = duration; 
     TaskId = id; 
    } 

    Task& predecessor(int index) const{ 

     for (std::vector<Task*>::iterator it = taskList.begin(); it != taskList.end(); ++it) { 
       //do stuff 
      } 
    } 

    } 

컴파일 나를 함수 이전의 루프에 대한 정의에 taskList.begin() 또는 taskList.end()를 쓸 수 없습니다. 컴파일러에서 알려줍니다.

내가해야 할 일이 무엇인지 말해 주시면 친절하십니까?

+2

const_iterator가 필요합니다. 'auto'를 사용하여 모든 것을 타이핑 할 필요가 없도록 제안합니다. –

답변

2

참고 predecessor이다 constpredecessor 내부 this -pointer가 consttaskListconst는 것을 의미하는 것을 의미한다. taskList.begin()std::vector<Task*>::iterator으로 변환 할 수없는 std::vector<Task*>::const_iterator을 반환합니다. 이는 const-correctness를 손상시킬 수 있기 때문입니다.

이 문제를 해결하려면 설명에 언급 된대로 std::vector<Task*>::const_iterator을 사용할 수 있습니다. 당신이 [C++ 11] 태그하지만 이후 더 나은 방법이있다 : 물론

//no need to worry about complicated types 
for (auto it = begin(taskList); it != end(taskList); ++it){ 
    //do stuff 
} 

//no need to worry about anything 
for (auto &&task : taskList){ 
    //do stuff 
} 

이 또한 그래서 당신은 predecessor에서 const을 제거하지 않는 it 또는 task 수없는 수정, CONST-정확성을 보존 할 수 있습니다.

+0

건배, 의미가 있습니다 :) – user4021524

0

predecessor 기능이 const이므로 aTask의 회원에 대한 액세스 권한도 const이어야합니다. it 변수는 std::vector<Task*>::const_iterator으로 선언해야하며, C++ 11에서는 auto을 사용할 수 있습니다.

Task& predecessor(int index) const { 
    for (auto it = taskList.begin(); it != taskList.end(); ++it) { 
     //do stuff 
    } 
} 
관련 문제