2011-06-14 2 views
1

여기서 "찾기"함수를 사용하려고합니다. 여기에 '=='연산자에 대한 코드가 있습니다. 그러나 "operator"라는 단어에서 "이 연산자 함수에 대해 너무 많은 매개 변수"오류가 발생합니다.C++의 Vector 구조에서 find 함수에 문제가 발생했습니다.

친절하게 도와 줄 수 있습니까? 감사.

struct gr_log 
{ 
    string name; 
    string category; 
    string description; 
    float cost; 
    bool operator==(const gr_log& l, const gr_log& r) const 

    { 
      return l.name == r.name; 
    } 

}; 

그리고 :

vector<gr_log>::iterator it; 
it = find (grocery.begin(), grocery.end(), "Sugar"); 

답변

4

회원 연산자는 하나 개의 인수한다 : 또는

struct gr_log 
{ 
    string name; 
    string category; 
    string description; 
    float cost; 
    bool operator==(const gr_log& r) 
    { 
     return name == r.name; 
    } 
}; 

을, 당신은 friend 운영자 작성할 수

struct gr_log 
{ 
    string name; 
    string category; 
    string description; 
    float cost; 
    friend bool operator==(const gr_log& l, const gr_log& r) 
    { 
     return l.name == r.name; 
    } 
}; 

또한 gr_log를 you'r과 같은 문자열과 비교할 수 없기 때문에 gr_log의 인스턴스를 사용하여 find을 수행해야합니다. 전자 일을하려고 :

it = find (grocery.begin(), grocery.end(), gr_log("Sugar")); 
+0

구조체에는 '친구'로 만들 필요가 없습니다. 연산자를 클래스 외부의 비회원으로 정의하면됩니다. –

+0

'친구'의 이유는 무엇입니까? – a1ex07

+0

@ a1ex07 :'friend'는'gr_log' (또는'friend'가 나타나는 클래스)의'private' 멤버에 대한 함수 접근을 제공합니다. 그것은 POD 구조체이기 때문에 모든 멤버는 public이며 'friend'는 혼란을 가져 오지만 아무것도하지 않습니다. –

0

연산자 ==는 구조의 구성원이 아니어야합니다. 이 경우 또는, this으로 1 개 인자를 가지고 비교해야한다 :

struct gr_log 
{ ... 
bool operator==(const gr_log& l) const {return name == r.name;} 
} 
//or outside of the structure 
bool operator==(const gr_log& l, const gr_log& r) 
{ 
     return l.name == r.name; 
} 
+0

그럼 어떻게해야합니까? – Ahsan

+0

@Ahsan : 업데이트 된 버전을 확인하십시오. – a1ex07

0

두 가지 선택이있다 : 함수 bool operator==(a,b)외부 구조체의, 또는 구조체 내부에 bool operator==(other) 중 하나.

3

이 시도 :

struct gr_log 
{ 
    string name; 
    string category; 
    string description; 
    float cost; 
    bool operator==(const string& name) { 
    return name == this->name; 
    } 
}; 

이것은 == 연산자 생성 (멤버 변수에 대한 올바른 신택스를 사용하여, 그것은 암시 this에 명시 적 인수 비교)를 stringgr_log 비교. std::find 호출은 문자열을 비교 객체로 사용하기 때문에 이동해야합니다. 당신은 헤더 파일에 다음을 가하고 있습니다 경우 inline 키워드가 있어야한다, 그러나 당신은 퍼팅하지 않을 경우 :

struct gr_log 
{ 
    string name; 
    string category; 
    string description; 
    float cost; 
}; 
inline bool operator==(const gr_log& gr, const string& name) { 
    return name == gr.name; 
} 
inline bool operator==(const sting& name, const gr_log& gr) { 
    return name == gr.name; 
} 

주 1 :

대안으로, 당신은 당신의 클래스 외부 평등 연산자를 정의 할 수 있습니다 소스 파일에서.

주 2 : 두 연산자 함수를 지정하면 동등한 상 동일 속성을 사용할 수 있습니다.

마지막 경우 이것은 충분히 위에 해싱되지 않은 - 멤버 항등 연산자 한 매개 변수를 상기 비 멤버 항등 연산자 걸린다.

관련 문제