【问题标题】:I have problems implementing the ++ increment operator [duplicate]我在实现 ++ 增量运算符时遇到问题 [重复]
【发布时间】:2015-04-19 23:54:38
【问题描述】:

我正在尝试为我刚刚完成的一个 c 库提供一个 c++ 接口,我希望它可以编写

for (DBITable table = db.tables() ; table != NULL ; table++)

其中db 是一个具有tables() 方法的类,该方法返回与之关联的DBITable

在编译时,clang++ 出现以下错误

error: cannot increment value of type 'DBITable'
for (DBITable table = db.tables() ; table != NULL ; table++)
                                                    ~~~~~^

这就是我实现++ 运算符重载方法的方式

DBITable
DBITable::operator++()
{
    return next();
}

它在DBITable 类中声明为

public:
    DBITable operator++();

table != NULL 部分按我的预期工作

bool operator!=(void *) 
{
    // evaluate and get the value
    return value;
}

【问题讨论】:

  • 本页顶部的图表应该会有所帮助:en.cppreference.com/w/cpp/language/operator_incdec
  • 为什么要为表类使用这样的运算符?运算符重载应该使代码更易于阅读。 “增加”或“推进”表格是什么意思?您的代码读者会熟悉这种解释吗?
  • @ChristianHackl 我稍后会更改班级名称。它在内部是一个链表。
  • 您可能希望使用预增量来避免不必要地复制迭代器。
  • @iharob:也有同样的问题。很容易想象一个列表迭代器是先进的,但肯定不是列表本身。事实上,std::list 没有 ++ 运算符,但它的迭代器有。

标签: c++ operator-overloading


【解决方案1】:

operator++() 是前缀递增运算符。将后缀运算符实现为operator++(int)

规范的实现是前缀运算符返回引用,后缀运算符按值返回。此外,您通常会根据前缀运算符来实现后缀运算符,以减少意外和易于维护。示例:

struct T
{
 T& operator++()
 {
  this->increment();
  return *this;
 }

 T operator++(int)
 {
   T ret = *this;
   this->operator++();
   return ret;
 }
};

(Increment/decrement operators at cppreference.)

【讨论】:

  • 非常非常简单... :) 当然,必须有一种方法来区分两者。我只是没有找到任何东西,@chris 发布的链接很好地解释了它。
  • @iharob:你不应该为这个错误负责。在我看来,这是所有庞大的 C++ 语言中最糟糕的设计决策。
  • @TonyK 同意我更喜欢Class::++operator()Class::operator++() 这样的东西会更明显。
  • @iharob: 或者在实现operator++ 时生成operator++(int) 编译器。
猜你喜欢
  • 2017-06-23
  • 1970-01-01
  • 2017-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 2012-11-23
相关资源
最近更新 更多