【问题标题】:C++/lists/iterators. Confusion over the word "other" within "const Text_iterator& other"C++/列表/迭代器。对“const Text_iterator& other”中的“other”一词感到困惑
【发布时间】:2016-10-13 21:59:07
【问题描述】:

在尝试定义“列表”以了解 C++ 列表如何按照 Stroustrup 的书 PPP 2nd ed 工作时。 刚刚出现了一个名为“other”的来历不明的词,我认为“other”这个词只是一个类 Text_iterator 对象的名称,但我不太明白它的用途。它是否试图将整个文本与另一个文本进行比较,以考虑打开不同文本的可能性?

class Text_iterator { // keep track of line and character position within a line
    list<Line>::iterator ln;
    Line::iterator pos;
public:
// start the iterator at line ll’s character position pp:
    Text_iterator(list<Line>::iterator ll, Line::iterator pp)
      :ln{ll}, pos{pp} { }
    char& operator*() { return *pos; }
    Text_iterator& operator++();
bool operator==(const Text_iterator& other) const
    { return ln==other.ln && pos==other.pos; }
bool operator!=(const Text_iterator& other) const
    { return !(*this==other); }
};
Text_iterator& Text_iterator::operator++()
{
    ++pos; // proceed to next character
    if (pos==(*ln).end()) {
        ++ln; // proceed to next line
        pos = (*ln).begin(); // bad if ln==line.end(); so make sure it isn’t
    }
    return *this;
}

【问题讨论】:

  • 你能不能...缩进你的代码?
  • 它是缩进的,选择和转换为代码的工具就是这样

标签: c++ list iterator line


【解决方案1】:

线索在于函数在做什么。我假设您指的是以下函数中的“其他”参数:

bool operator==(const Text_iterator& other) const

bool operator!=(const Text_iterator& other) const

这些是相等和不等运算符的运算符重载。例如

my_object == other_object
my_object != other_object

所以“其他”是比较中的“其他对象”。

【讨论】:

    【解决方案2】:
    // This is the name of a parameter---V
    bool operator==(const Text_iterator& other) const
    { return ln==other.ln && pos==other.pos; }
    // And so it this -------------------V
    bool operator!=(const Text_iterator& other) const
    { return !(*this==other); }
    

    您可以随意命名参数,只要它不与语言关键字冲突并且以字母或下划线开头。

    例如,这将是一个与other 一样好的参数名称:

    bool operator==(const Text_iterator& anotherIterator) const
    { return ln==anotherIterator.ln && pos==anotherIterator.pos; }
    

    并且该方法(实际上是== 运算符)旨在比较两个Text_iterator 是否相等,即:'它们是否指向文本中的相同位置?'

    [编辑]

    bool operator!=(const Text_iterator& other) const
    { return !(*this==other); }
    

    operator == 正好相反,因此它旨在回答“两个迭代器是否指向文本中的不同位置?”的问题。由于它只是一个否定,因此只需调用operator ==并否定结果即可实现最快和最安全。

    (“以防万一”注):至于*this - 您需要了解this(它是一个指针)和*this 之间的区别,它是一个引用。这件事对你在 C++ 中的进步至关重要,所以尽早而不是迟到。

    【讨论】:

    • 这部分怎么样? :S 返回 !(*this==other)
    • @Kenzo 添加了解释
    猜你喜欢
    • 1970-01-01
    • 2010-10-29
    • 2015-07-12
    • 2012-10-14
    • 2018-10-18
    • 2011-10-17
    • 2016-04-08
    • 2020-09-18
    • 2022-11-25
    相关资源
    最近更新 更多