我正在为我的容器定义迭代器类型,当然我希望iterator
可转换为const_iterator
。但我不确定哪个更好/更好:iterator
中的转换运算符
class iterator
{
operator const_iterator();
};
或
const_iterator
中的非显式构造函数class iterator
{
// implementation
friend class iterator; // hard to avoid this
};
class const_iterator
{
const_iterator(iterator const &);
};
有什么指南哪种方法更好?
最佳答案
仅当可以在不构造新对象的情况下返回所需类型,或者其返回值是简单数据类型时,才应编写转换运算符。例如,如果要返回对该类内某个属性的const引用,则应将其编写为强制转换运算符。
在所有其他情况下,您应该只编写适当的构造函数。
关于c++ - 给定类型的转换运算符与构造函数。哪个更好?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6095802/