有一个time 类,包括数据成员minute ,sec模拟秒表,每次走一秒,满60秒进一分钟,此时秒从0起算
#include <iostream>
using namespace std;
class Time
{
private ://私有数据成员
int sec;//秒
int minute;//分
public://公有数据
Time () {
minute=0;
sec=0;
}//默认构造函数初始化
Time (int a,int b) {
minute=a;
sec=b;//有参数的构造函数
}
Time operator ++() ;//声明重载函数作为类成员函数
void display () ;//声明输出函数
};
void Time::display() //类外定义输出函数
{
cout<<minute<<": "<<sec<<endl;
}
Time Time::operator++()
{
//类外定义重载函数
if(++sec>=60)
{
sec-=60;//秒位置发生变化
++minute;//分位置发生进位
}
return *this;//!!!注意一定要返回this 指针 因为它的返回为一个类的对象所以要加星花
}
int main()
{
Time t(34,0);//建立一个类对象
for(int i=0;i<61;i++)
{
++t;//使用重载后的符号
t.display();//进行输出
}
return 0;
}
前面重载了++运算符号,但是注意++分为前置和后置,它们的功能是不同的所以重载也有区别,c++系统会根据需要来调用不同的函数,接下来,我们看看后置++运算符怎么重载,以及和前置++的区别
#include <iostream>
using namespace std;
class Time
{
private ://私有数据成员
int sec;//秒
int minute;//分
public://公有数据
Time () {
minute=0;
sec=0;
}//默认构造函数初始化
Time (int a,int b) {
minute=a;
sec=b;//有参数的构造函数
}
Time operator ++(int) ;//声明重载函数作为类成员函数
void display () ;//声明输出函数
};
void Time::display() //类外定义输出函数
{
cout<<minute<<": "<<sec<<endl;
}
Time Time::operator++(int) //不能用引用防止成为野指针
{
//类外定义重载函数
Time temp(*this);//定义一个临时对象
sec++;
if(sec>=60)
{
sec-=60;//秒位置发生变化
++minute;//分位置发生进位
}
return temp;//返回的是自加前的对象
}
int main()
{
Time t(34,0),t2;//建立一个类对象
cout<<"t";
t.display();
cout<<endl;
t2=t++;//将自加前的对象值赋值
cout<<"t2:"<<" " ;
t2.display();
cout<<endl;
cout<<"t++";
t.display();
return 0;
} 可以看到后置自加运算符号多了int型的参数