c++,前缀递增,和后缀递增运算符都怎么重载?

2025-04-08 09:20:25
推荐回答(1个)
回答1:

#include <iostream.h>

class counter
{
public:
counter() { v=0; }
counter operator ++();
counter operator ++(int );
void print() { cout<<v<<endl; }
private:
unsigned v;
};

counter counter::operator ++()
{
v++;
return *this;
}

counter counter::operator ++(int)
{
counter t;
t.v = v++;
return t;
}

void main()
{
counter c;
for(int i=0; i<8; i++)
c++;
c.print();
for(i=0; i<8; i++)
++c;
c.print();
}