rco*_*rie 0 c++ class operator-overloading postfix-operator
我正在尝试重载' - '后缀运算符.我有这个代码:
class Counter
{
private:
int count;
public:
Counter()
{ count = 0; }
Counter(int c)
{ count = c; }
void setCount(int c)
{ count = c; }
int getCount()
{ return count; }
int operator--()
{
int temp = count;
count = count - 1;
return temp;
}
};
Run Code Online (Sandbox Code Playgroud)
然后在main我有这个函数调用:
Counter a;
a.setCount(5);
cout << a-- << endl;
Run Code Online (Sandbox Code Playgroud)
这给了我这个错误:
error: no ‘operator--(int)’ declared for postfix ‘--’, trying prefix operator instead
但是当我这样调用这个operator--函数时,它运行得很好:
cout << a.operator--() << endl;
Run Code Online (Sandbox Code Playgroud)
是什么赋予了?它应该工作正常.
后缀运算符使用int一个参数来区分它与前缀运算符.
后缀:
int operator--(int)
{
}
Run Code Online (Sandbox Code Playgroud)
字首:
int operator--()
{
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3486 次 |
| 最近记录: |