2017-01-20 95 views
0

我目前工作的一個集類在C++當然這是從vector<T>推導默認參數。方法作爲一種方法

在我來到這裏我需要實現一個名爲index()功能這顯然會返回(如果該集合包含的話),這些組中的對象的指數點一個點。 在寫全班我來到這裏我需要重載這些index()方法,這其中包括公共點。 因此,這裏有我的兩類方法: 1日。 3個PARAMS:

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); 

} 

第二屆一個PARAM:

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

關鍵是我不想寫這2種方法,它可能如果有可能被合併成一個。我想到了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.

也許我錯過ED的事情,但是請讓我知道如果你誰能告訴我要麼是可以調用的方法作爲默認PARAM,還是不行。

回答

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所以沒有辦法做到這一點? –

相關問題