【发布时间】:2019-12-31 22:00:20
【问题描述】:
当我重载后减运算符时,我必须包含一个额外的参数:
#include <iostream>
template<class T>
class wrap
{
public:
bool operator >(T &&v)
{
return value > v;
}
T operator --(int v) // Remove 'int v' and you get a compilation error
{
return (value -= 1) + 1;
}
wrap(T v)
{
value = v;
}
private:
T value;
};
int main(void)
{
wrap<int> i(5);
while(i --> 0)
std::cout << "Why do we need the extra argument?\n";
return 0;
}
如果我删除这个看似不需要的参数,我会收到编译错误:
test.cpp: In function ‘int main()’: test.cpp:26:13: error: no ‘operator--(int)’ declared for postfix ‘--’ [-fpermissive] while(i --> 0) ~~^~
这个参数有什么用?它的价值代表什么?
【问题讨论】:
-
引用重复中的答案确实解释了
int参数是一个虚拟变量。
标签: c++ operator-overloading decrement postfix-operator