所谓单目运算符,是指运算的对象或者变量只有一个。比如:
a++;
b--;
在c++语言中,当参加运算的是对象时,需要使用重载单目运算符函数。
首先给出类的定义:
class FeetInches
{
private:
int feet, inches;
public:
void display()
{
cout<<feet<<"."<<inches<<endl;
}
FeetInches(int f,int i)
{
feet=f;
inches=i;
}
FeetInches operator++(); //重载前置++运算符
FeetInches operator++( int ); //重载后置++运算符,注意到括号里面有一个哑元。这是区分前后置的关键
};
接下来编写函数:
前置++是先加后用
FeetInches FeetInches::operator++( )
{
++inches;
return *this;
} //前置++比较简单,直接返回*this即可
后置++是先用后加,所以编写上与前置++有所区别:
FeetInches FeetInches::operator++(int)
{
FeetInches temp(feet, inches); //定义一个temp变量,用当前对象来初始化它。
inches++; //执行++操作。
return temp; //因为是先使用后加,所以返回改变之前的值,此时当前变量已经改变。
}
以上就是++运算符的重载,类比可写出--运算符重载。
完整代码:
#include<iostream>
using namespace std;
class FeetInches
{
private:
int feet, inches;
public:
void display()
{
cout<<feet<<"."<<inches<<endl;
}
FeetInches(int f,int i)
{
feet=f;
inches=i;
}
FeetInches operator++( );
FeetInches operator++( int );
};
FeetInches FeetInches::operator++( )
{
++inches;
return *this;
}
FeetInches FeetInches::operator++(int)
{
FeetInches temp(feet, inches);
inches++;
return temp;
}
int main()
{
FeetInches f1(1,3),f2(2,4),f3(0,0),f4(0,0);
f3=f1++;
f4=++f2;
f1.display();
f2.display();
f3.display();
f4.display();
return 0;
}