问题描述
我正在为我的容器定义迭代器类型,当然,我希望 iterator
可转换为 const_iterator
。但我不确定哪个更好/更可取:
I'm defining iterator types for my container and of course I want iterator
to be convertible to const_iterator
. But I'm not sure which is better/preferable:
iterator
class iterator
{
operator const_iterator();
};
或 const_iterator
or non-explicit constructor in const_iterator
class iterator
{
// implementation
friend class iterator; // hard to avoid this
};
class const_iterator
{
const_iterator(iterator const &);
};
有没有什么指南是更好的方法?
Are there any guidelines which way is better?
推荐答案
仅当可以在不构造新对象的情况下返回期望的类型,或者返回的是简单数据类型时,才应编写转换运算符。例如,如果要返回对类内某个属性的const引用,则应将其编写为强制转换运算符。
You should write a casting operator only if it is possible to return the desired type without constructing a new object, or if its return is a simple data type. For example, if it were to return a const reference to a property within the class, then you should write it as a casting operator.
在所有其他情况下,都应只需编写适当的构造函数即可。
In all other cases, you should just write the appropriate constructor.
这篇关于给定类型的转换运算符与构造函数。哪个更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!