//头文件
#ifndef FRIEND_H
#define FRIEND_H
#include
namespace FRIEND{
class Friend{
private:
int hour;
int minute;
public:
Friend();
Friend(int h, int m);
~Friend();
void setHour(int h){ hour = h; }
int getHour() const { return hour; }
void setMinute(int m){ minute = m; }
int getMinute() const{ return minute; }
//重载操作符必须把定义类放在一起,要不然会报链接错误
Friend operator +(const Friend &f) const
{
Friend fr;
fr.hour = f.hour+hour;
fr.minute = f.minute + minute;
if (fr.minute >= 60)
{
fr.hour += 1;
fr.minute %= 60;
}
fr.setHour(fr.hour);
fr.setMinute(fr.minute);
return fr;
}
//<<操作符的重载必须声明为友元函数,因为ostream对象不是当前类的对象,而操作符的重载是隐式调用<<前面的对象,
//而显示调用<<后面的对象两个对象并不是同一种类型的时候就不写为当前类的函数
friend std::ostream &operator <<(std::ostream &os, const Friend &f)
{
os << f.getHour() << "小时; " << f.getMinute() << "分钟; " << std::endl;
return os;
}
};
}
#endif
//定义文件
#include
#include "Friend.h"
using namespace std;
using namespace FRIEND;
Friend::Friend()
{
hour = minute = 0;
}
Friend::Friend(int h, int m)
{
this->hour = h;
this->minute = m;
}
Friend::~Friend()
{
}
//主函数
#include
#include "Friend.h"
using namespace std;
using namespace FRIEND;
int main()
{
Friend f1(2,20);
Friend f2 ;
Friend f3(2,50);
Friend *fr = new Friend;
fr->setHour(5);
fr->setMinute(29);
cout << "f1:" << f1 << endl;
cout << "f2:" << f2 << endl;
cout << "f1+f3:" << (f1+f3 )<< endl;
cout << "f3:" << f3 << endl;
cout << "fr:" << *fr << endl;
delete fr;
system("pause");
return 0;
}
结果
有两点:
1、重载的+操作符是隐式调用操作符前面的对象而显示调用后面的对象,比如:object1+object2,相当于是这样调用 的,bojcet1.operator+(object2);
所以如果前后两个对象不同的时候在类里定义的时候,必须声明为友元函数。
2、声明和定义必须放在同一个文件下,不然会报链接错误(2109),我亲自试了。
刚写的C++关于重载+和<<运算…
最新推荐文章于 2024-05-29 16:57:56 发布