三目运算符不能重载
用成员函数形式重载运算符“++”“–”
#include<iostream>
using namespace std;
class Counter
{
public:
Counter()
{
value=0;
}
Counter(int i)
{
value=i;
}
Counter operator ++();
Counter operator ++(int);
Counter operator --();
Counter operator --(int);
void display()
{
cout<<value<<endl;
}
private:
unsigned value;
};
Counter Counter::operator ++()
{
value++;
return *this;
}
Counter Counter::operator ++(int)
{
Counter temp;
temp.value=value++;
return temp;
}
Counter Counter ::operator --()
{
value--;
return *this;
}
Counter Counter ::operator--(int)
{
Counter temp;
temp.value=value--;
return temp;
}
int main()
{
Counter n(10),c;
c=++n;
cout<<"前缀++运算符计算结果:"<<endl;
cout<<"n= ",n.display();
cout<<"c= ",c.display();
c=n++;
cout<<"后缀++运算符计算结果:"<<endl;
cout<<"n= ",n.display();
cout<<"c= ",c.display();
c=--n;
cout<<"前缀--运算符计算结果:"<<endl;
cout<<"n= ",n.display();
cout<<"c= ",c.display();
c=n--;
cout<<"后缀--运算符计算结果:"<<endl;
cout<<"n= ",n.display();
cout<<"c= ",c.display();
return 0;
}
结果:
前缀++运算符计算结果:
n= 11
c= 11
后缀++运算符计算结果:
n= 12
c= 11
前缀--运算符计算结果:
n= 11
c= 11
后缀--运算符计算结果:
n= 10
c= 11