【发布时间】: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没有++运算符,但它的迭代器有。