我想知道怎么std::vector::begin()
或者类似的方法实际上可以针对不同的返回类型(const 和非 const 迭代器)进行重载,如
std::vector<int>::iterator it = vect.begin();
和std::vector<int>::const_iterator cit = vect.begin();
因为,仅返回类型不同的函数不能被重载。然后我看了一眼stl_vector.h
并发现这是可能的,因为其中一个功能是 const
.
324 /** |
325 * Returns a read/write iterator that points to the first |
326 * element in the %vector. Iteration is done in ordinary |
327 * element order. |
328 */ |
329 iterator |
330 begin() |
331 { return iterator(this->_M_impl._M_start); } |
332 |
333 /** |
334 * Returns a read-only (constant) iterator that points to the |
335 * first element in the %vector. Iteration is done in ordinary |
336 * element order. |
337 */ |
338 const_iterator |
339 begin() const |
340 { return const_iterator(this->_M_impl._M_start); } |
341 |
342 /** |
343 * Returns a read/write iterator that points one past the last |
344 * element in the %vector. Iteration is done in ordinary |
345 * element order. |
346 */ |
然后我尝试在测试程序中模仿这个结构,但出现了一个令我困惑的错误,因为逻辑看起来与我相同:
struct A
{
};
struct B
{
};
struct C
{
A f() const {
std::cout << "A" << "\n";
return A();
}
B f() {
std::cout << "B" << "\n";
return B();
}
};
int main(){
C c;
A x = c.f();
}
error: no viable conversion from 'B' to 'A'
A x = c.f();
该方法返回 B
被调用,为什么编译器不从 A x
推导出来需要调用另一个方法,我的测试程序和 STL_vector 代码有什么区别?
最佳答案
您没有看到重载,而是看到相关 iterator
之间的转换。和const_iterator
类型:
std::vector<int>::const_iterator cit = vect.begin();
如果vect
是非常量,那么 vect.begin()
返回 vector<int>::iterator
,然后可以转换为 vector<int>::const_iterator
。出于常量正确性的原因,不允许反向转换。
这与 const
的问题很大程度上无关。成员函数的限定,这确实允许重载。
关于c++ - 使用 const 关键字重载签名相同的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39895765/