class Time
{
private:
int hours = 3; //c++ 11 允许这样的定义
int mins = 2;
public:
Time(int = 2, int = 3);
Time(const Time & a);
~Time();
void show();
Time operator+(const Time & a)const;
};
c++ 11 中允许在类的声明中将私有成员赋值,但是这样做很蠢,我觉得毛用没有,因为类中只有一个默认构造函数,用Time()就不能传参,用Time(int = 2,int = 3)完全也没必要在类的声明中那样做,所以我不会在声明中初始私有成员变量,可能他一定不改变的时候会用?` 下面是类的cpp文件和main函数,我合在一起了
#include <iostream>
#include"time.h"
using namespace std;
Time::Time(int h, int m)
{
hours = h;
mins = m;
}
Time::Time(const Time & a)
{
hours = a.hours;
mins = a.mins;
}
Time::~Time()
{
cout << "Time is over " << hours << mins << endl;
}
Time Time:: operator+(const Time & a)const
{
Time sum;
sum.hours = hours + a.hours;
sum.mins = mins + a.mins;
return sum;
}
void Time::show()
{
cout << hours << "," << mins << endl;
}
int main()
{
Time old;
Time new1(1, 2);
Time new2(new1);
old.show();
new1.show();
Time haha = old + new1;
haha.show();
new2.show();
}