2016-04-24 43 views
0

我試圖弄清楚爲什麼當你訪問名爲asdf的std::set的數組時,這段代碼不能編譯。但是,如果您嘗試訪問asdf的元素(如本示例中的索引0),則無法使用函數getItem編譯代碼。編譯器會拋出這個錯誤。std :: set和比較器數組

main.cpp(21): error C2440: 'return': cannot convert from 'const std::set<test *,test::compare,std::allocator<_Kty>>' to 'const std::set<test *,std::less<_Kty>,std::allocator<_Kty>> &' 
     with 
     [ 
      _Kty=test * 
     ] 
main.cpp(21): note: Reason: cannot convert from 'const std::set<test *,test::compare,std::allocator<_Kty>>' to 'const std::set<test *,std::less<_Kty>,std::allocator<_Kty>>' 
     with 
     [ 
      _Kty=test * 
     ] 
main.cpp(21): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called 

這裏是例子:

#include <set> 

struct test { 
    int idx; 
    struct compare { 
     bool operator()(const test* a, const test* b) { 
      return a->idx < b->idx; 
     } 
    }; 
}; 


class asdf123 { 
public: 
    asdf123() { 

    } 

    const std::set<test*>& getItem() const 
    { 
     return asdf[0]; 
    } 

private: 
    typedef std::set<test*, test::compare> stuffType[100]; 
    stuffType asdf; 
}; 

int main() { 
    asdf123 a; 
    return 0; 
} 

沒有代碼工作正常的比較。

回答

0

std::set<test*, test::compare>std::set<test*>是不同的類型,不能隱式地從一個轉換到另一個,這就是編譯器抱怨的原因。

std::set有兩個默認的模板參數,所以std::set<test*, test::compare>

std::set<test*, test::compare, std::allocator<test*>> 

std::set<test*>

std::set<test*, std::less<test*>, std::allocator<test*>> 

你可能的getItem()返回類型更改爲const std::set<test*, test::compare>&來解決這個問題。

+1

您可能想對此進行擴展:沒有從這兩種類型到另一種類型的隱式轉換,因此編譯錯誤。 – Peter

+0

哇,我怎麼錯過他們有不匹配的類型?我想我更關注於試圖找出隱藏的編譯器錯誤是什麼。 –

+0

@BrandanTylerLasley錯誤消息中仍然有提示,尤其是它顯示了未能轉換的兩種類型, – songyuanyao