#include <iostream>
using std::string;
using std::cout;
using std::endl;
class Time
{
public:
int hours;
int minutes;
int seconds;
Time(int h, int m, int s)
: hours(h), minutes(m), seconds(s)
{
cout << hours << ":" << minutes << ":" << seconds << endl;
}
//类内重载运算符
Time operator+(const Time& t)
{
cout << "类内重载 + operator" << endl;
int newHours = this->hours + t.hours;
int newMinutes = this->minutes + t.minutes;
int newSeconds = this->seconds + t.seconds;
if (newSeconds >= 60)
{
newMinutes += newSeconds / 60;
newSeconds %= 60;
}
if (newMinutes >= 60)
{
newHours += newMinutes / 60;
newMinutes %= 60;
}
if (newHours >= 24)
{
newHours %= 24;
}
return Time(newHours, newMinutes, newSeconds);
}
// 类内重载 << operator
//此处的firend关键字是必须的,因为cout不是Time的成员函数
//在C++中,<< 运算符通常用于输出流,为了使用<<运算符输出Time对象,需要重载<<运算符
friend std::ostream &operator<<(std::ostream &os,const Time &t)
{
os << t.hours << ":" << t.minutes << ":" << t.seconds << endl;
return os;
}
~Time()
{
cout << "时间的析构函数" << endl;
}
};
// 类外重载 + operator
Time operator+( Time& t1, Time& t2)
{
cout << "类外重载 + operator" << endl;
int newHours = t1.hours + t2.hours;
int newMinutes = t1.minutes + t2.minutes;
int newSeconds = t1.seconds + t2.seconds;
if (newSeconds >= 60)
{
newMinutes += newSeconds / 60;
newSeconds %= 60;
}
if (newMinutes >= 60)
{
newHours += newMinutes / 60;
newMinutes %= 60;
}
if (newHours >= 24)
{
newHours %= 24;
}
return Time(newHours, newMinutes, newSeconds);
}
int main(int argc, char const *argv[])
{
Time t1(11,50,25);
Time t2(2,30,45);
//Time t3 = t1 + t2; // 类外重载
Time t3 = t1.operator+(t2); // 类内重载
cout << "--------" << endl;
cout << t3 ; //通过类内重载 << operator 输出
return 0;
}
在C++中,friend
关键字用于声明一个友元函数或友元类。友元函数或友元类可以访问类的私有成员和保护成员,即使它们不是类的成员函数或成员类。