我在实现 ++ 增量运算符时遇到问题
I have problems implementing the ++ increment operator
我正在尝试为我刚刚完成的 c 库提供一个 c++ 接口,我希望它可以编写
for (DBITable table = db.tables() ; table != NULL ; table++)
其中 db
是具有 tables()
方法的 class,returns DBITable
与其关联。
编译时出现以下错误 clang++
error: cannot increment value of type 'DBITable'
for (DBITable table = db.tables() ; table != NULL ; table++)
~~~~~^
这就是我实现 ++
运算符重载方法的方式
DBITable
DBITable::operator++()
{
return next();
}
并且它在 DBITable
class 中声明为
public:
DBITable operator++();
table != NULL
部分按我预期的那样工作
bool operator!=(void *)
{
// evaluate and get the value
return value;
}
operator++()
是前缀增量运算符。将后缀运算符实现为 operator++(int)
.
规范的实现有前缀运算符 return 作为参考,后缀运算符 return 作为值。此外,为了减少意外和易于维护,您通常会根据前缀运算符来实现后缀运算符。示例:
struct T
{
T& operator++()
{
this->increment();
return *this;
}
T operator++(int)
{
T ret = *this;
this->operator++();
return ret;
}
};
我正在尝试为我刚刚完成的 c 库提供一个 c++ 接口,我希望它可以编写
for (DBITable table = db.tables() ; table != NULL ; table++)
其中 db
是具有 tables()
方法的 class,returns DBITable
与其关联。
编译时出现以下错误 clang++
error: cannot increment value of type 'DBITable'
for (DBITable table = db.tables() ; table != NULL ; table++)
~~~~~^
这就是我实现 ++
运算符重载方法的方式
DBITable
DBITable::operator++()
{
return next();
}
并且它在 DBITable
class 中声明为
public:
DBITable operator++();
table != NULL
部分按我预期的那样工作
bool operator!=(void *)
{
// evaluate and get the value
return value;
}
operator++()
是前缀增量运算符。将后缀运算符实现为 operator++(int)
.
规范的实现有前缀运算符 return 作为参考,后缀运算符 return 作为值。此外,为了减少意外和易于维护,您通常会根据前缀运算符来实现后缀运算符。示例:
struct T
{
T& operator++()
{
this->increment();
return *this;
}
T operator++(int)
{
T ret = *this;
this->operator++();
return ret;
}
};