gpt4 book ai didi

c++ - 错误 : passing ‘const Vector’ as ‘this’ argument of . .. 丢弃限定符 [-fpermissive]

转载 作者:行者123 更新时间:2023-11-28 05:23:01 25 4
gpt4 key购买 nike

最近在研究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); }

关于c++ - 错误 : passing ‘const Vector<int>’ as ‘this’ argument of . .. 丢弃限定符 [-fpermissive],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41072957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com