2017-01-20 11 views
0

현재 vector<T>에서 파생 된 C++ 코스의 Set-class에서 작업하고 있습니다.메소드의 기본 매개 변수로 사용되는 메소드

한 지점에서 필자는 index()이라는 함수를 구현해야 할 시점에이 집합 내의 개체 인덱스를 분명히 반환합니다 (집합에 포함 된 경우). 전체 클래스를 쓰는 동안 나는이 두 가지 오버로드 방법을 모두 오버로드해야합니다. 두 가지 유형의 메소드가 있습니다. 1st. 하나 PARAM와

size_t index (T const& x,size_t const& l, size_t const& r) const 
{ 

    if(l > size()||r>size()) 
     throw("Menge::index(): index out of range."); 

    //cut the interval 
    size_t m = (l+r)/2; 

    // x was found 
    if(x == (*this)[m]) 
     return m; 

    // x can't be found 
    if(l==m) 
     return NPOS; 

    //rekursive part 
    if(x < (*this)[m]) 
     return index(l,m,x); 

    return index(m+1,r,x); 

} 

2 : 3 PARAMS 가능한 경우

bool contains (T const& elem) const{ 
    return index(elem, 0, size()-1)!=NPOS; 
} 

요점은 내가이이 방법을 쓰고 싶지 않아, 그것은이 하나로 결합 될 수있다. 나는 index() 방법에 대한 기본값 생각, 그래서 내가 좋아하는 방법 헤드 작성합니다 나에게 오류 준

size_t index (T const& x, size_t const& l=0, size_t const& r=size()-1)const; 

: 해당 오류에 대해 생각하면 Elementfunction can't be called without a object

, 나는에 해봤를 에 편집 :

size_t index (T const& x, size_t const& l=0, size_t const& r=this->size()-1)const; 

그러나 그것은 나에게 오류 준 : 내가 그리워 어쩌면 You're not allowed to call >>this<< in that context.

을 에드,하지만, 만약 당신이 누군가가 기본 매개 변수로 메소드를 호출 할 수 있는지 또는 말해 줄 수 있는지 알려주세요.

답변

1

기본 인수를 정의 할 때 this을 사용할 수 없습니다.

The this pointer is not allowed in default arguments source .

일반적인 방법은 적은 양의 매개 변수로 오버로드를 제공하는 것입니다. 이는 과도한 부담을 피하기 위해 필요한 초기 상황입니다.

size_t index (T const& x,size_t const& l, size_t const& r) const; 
size_t index (T const& x) const { 
    index(x, 0, size() - 1); 
} 

다른 방법으로 구현에서 테스트 할 수있는 기본 인수로 마법 번호를 할당하는 방법을 고려해 볼 수 있습니다.

#include <limits> 

constexpr size_t magic_number = std::numeric_limits<size_t>::max(); 

size_t index (T const & x, size_t l = 0, size_t r = magic_number) const 
{ 
    if(r == magic_number) { 
     r = size() - 1; 
    } 

    // Actual implementation 
} 
+0

* 기본 매개 변수 값은 컴파일시의 상수 여야합니다. * 사실이 아닙니다. http://ideone.com/PWFFHS를 참조하십시오. –

+0

@RSahu 수정 해 주셔서 감사합니다. –

+0

@RSahu 그렇게 할 방법이 없습니까? –