常成员函数与常对象

来源:互联网 发布:销售管理系统源码 编辑:程序博客网 时间:2024/04/28 14:33

在读一个朋友写的代码时终于弄明白了一些关于const的语法。

1、如果是const修饰的常对象,则它只能使用它的常成员函数。

2、如果对象没有加const它既可以用常函数又可以用它的非常成员函数。

(另外说一些小小需要注意的地方:在用友元时头文件为<.h>并且不用加using namespace std;)

下面用我的朋友的代码举例说明:

#include<iostream.h>
#include<iomanip.h>

 

class Time
{
  int hour,minute,second;
public:
 int SecCalc()const {  return  (hour*60+minute)*60+second; }        //加const后成为常成员函数
  
  Time(int h=0,int m=0, int s=0);
  void SetTime(int h=0,int m=0, int s=0);
  void print_12();
  void print_24();
friend Time operator+ ( const Time t, const Time m);
friend Time operator+(const Time t,int m);
friend Time operator+(int m,const Time t);
friend Time operator-(const Time t,const Time m);
friend Time operator-(const Time t,int m);
};
Time::Time(int h,int m,int s)
{
 hour=h;
 minute=m;
 second=s;
}
void Time::SetTime(int h,int m,int s)
{
 hour=h;
 minute=m;
 second=s;
}
void Time::print_12()
{
 if(hour>12)
  cout<<setfill('0')<<setw(2)<<hour%12<<':'<<setw(2)<<minute<<':'<<setw(2)<<second<<setfill(' ')<<' '<<"PM";
 if(hour<=12)
  cout<<setfill('0')<<setw(2)<<hour<<':'<<setw(2)<<minute<<':'<<setw(2)<<second<<setfill(' ')<<' '<<"AM";
}
void Time::print_24()
{
  cout<<setfill('0')<<setw(2)<<hour<<':'<<setw(2)<<minute<<':'<<setw(2)<<second<<setfill(' ');
}
Time operator+(const Time t,const Time m)        //time类的t 加const修饰成为常对象,此时在它使用的SecCalc()函数只能为常函数
{
 Time a;int b;
 b=t.SecCalc()+m.SecCalc();
 a.second=b%60;b/=60;
 a.minute=b%60;b/=60;
 a.hour=b%60;
    return a;
}
Time operator+(const Time t,int n)
{
 Time a;int b;
 b=t.SecCalc()+n;
 a.second=b%60;b/=60;
 a.minute=b%60;b/=60;
 a.hour=b%60;
    return a;
}
Time operator+(int n, Time t//time类的t 不加const修饰不是常对象,此时在它使用的SecCalc()函数可以为常函数也可以不是不加const的非常函数

{
 Time a;int b;
 b=t.SecCalc()+n;
 a.second=b%60;b/=60;
 a.minute=b%60;b/=60;
 a.hour=b%60;
    return a;
}
Time operator-(const Time m,const Time t)
{
 Time a;
 int b;
 b=t.SecCalc()-m.SecCalc();
 a.second=b%60;b/=60;
 a.minute=b%60;b/=60;
 a.hour=b%60;
 return a;
}
Time operator-(const Time t,int n)
{
 Time a;
 int b;
 b=t.SecCalc()-n;
 a.second=b%60;b/=60;
 a.minute=b%60;b/=60;
 a.hour=b%60;
 return a;
}
int main()
{
  Time t1(2,34),t2,t3;
  t2.SetTime(13,23,34);
  cout<<"\nt1+t2:";
  t3=t1+t2;  //两个Time类对象相加
  t3.print_24();
  cout<<"\nt1+65:";
  t3=t1+65;  //Time类对象加上65秒
  t3.print_24();
  cout<<"\n65+t1:";
  t3=65+t1;  //65秒加上Time类对象
  t3.print_24(); 
  cout<<"\nt1-t2:";
  t3=t1-t2;  //两个Time类对象相减
  t3.print_24();
  cout<<"\nt1-70:";
  t3=t1-70;  //Time类对象减去70秒
  t3.print_24(); 
  return 0;
}

 

原创粉丝点击