簡體   English   中英

錯誤:傳遞&#39;const Vector <int> 作為...的&#39;this&#39;參數,將丟棄限定詞[-fpermissive]

[英]error: passing ‘const Vector<int>’ as ‘this’ argument of … discards qualifiers [-fpermissive]

我最近試圖弄清楚SGI STL,並且編寫了自己的Vector,但是用簡單的測試代碼卻遇到了麻煩。 當我嘗試編譯它時,它抱怨像這樣:

error: passing ‘const Vector<int>’ as ‘this’ argument of 
‘Vector<T,Alloc>::value_type* Vector<T, Alloc>::end() 
[with T = int; Alloc = __default_alloc_template<false, 0>; Vector<T, Alloc>::iterator = int*; Vector<T, Alloc>::value_type = int]’ 
discards qualifiers [-fpermissive]
size_type size() const { return size_type(end() - begin()); }

我查看了const函數的用法,它表示如果代碼不更改類中的任何成員,則它可以是const函數。

我真的不明白,size()不會更改Vector中的任何成員,只是調用其他兩個函數。

我檢查了SGI_vector,我認為它與我的代碼完全相同。

它出什么問題了? 謝謝!

int main(){
    Vector<int> v2;
    cout<<"sizeof(v2): "<<v2.size()<<endl;
    return 0;
}

我已經這樣寫了自己的Vector:

template <class T, class Alloc = alloc>
class Vector {//primary template
public:
    typedef T value_type;
    typedef value_type* iterator;
    typedef size_t  size_type;

protected:
    typedef simple_alloc<value_type,alloc> data_allocator;
    iterator start;
    iterator finish;
    iterator end_of_storage;

public:
    iterator begin(){return start;}
    iterator end()  { return finish; }
    size_type size() const { return size_type(end() - begin()); }
    Vector():start(0),finish(0), end_of_storage(0){}
};

size()const成員函數。 通過此函數,您只能調用其他const成員函數。 不允許在size()中調用begin()end() ,因為begin()end()是非const成員函數。

您可以只使用成員變量startfinish來實現size()

size_type size() const { return size_type(finish - start); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM