刚写的C++关于重载+和<<运算…

//头文件
#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;
}
结果
刚写的C++关于重载+和<<运算符和一个范例,不解释

有两点:
1、重载的+操作符是隐式调用操作符前面的对象而显示调用后面的对象,比如:object1+object2,相当于是这样调用 的,bojcet1.operator+(object2);
所以如果前后两个对象不同的时候在类里定义的时候,必须声明为友元函数。
2、声明和定义必须放在同一个文件下,不然会报链接错误(2109),我亲自试了。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不识君的荒漠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值