【带头学C++】----- 九、类和对象 ---- 9.13 运算符重载——(9.13.5-9.13.6)

❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️创做不易,麻烦点个关注❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️

❤️❤️❤️❤️❤️❤️❤️❤️❤️文末有惊喜!献舞一支!❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️

9.13.5 重载+运算符(全局函实现)

上节实现了<<、>>输入输出运算符重载,那么我们怎么实现下面这样的情况呢?

 【带头学C++】----- 九、类和对象 ---- 9.13 运算符重载——(9.13.5-9.13.6)_第1张图片

这里就是上一节我们输出的时候,第二参数传的是引用类型。

【带头学C++】----- 九、类和对象 ---- 9.13 运算符重载——(9.13.5-9.13.6)_第2张图片

结果:

【带头学C++】----- 九、类和对象 ---- 9.13 运算符重载——(9.13.5-9.13.6)_第3张图片

代码:

#include 
#include 
#include "array.h"

using namespace std;
class Person
{
    friend ostream& operator<<(ostream &out,Person ob);
    friend istream& operator>>(istream &in,Person &ob);
    friend Person operator+(Person &ob1,Person &ob2);
private:
    int num;
    string name;
    float score;
public:
    Person(){}
    Person(int num,string name,float score):num(num),name(name),score(score){}
};
//全局函数重载operator<< 输出运算符
ostream& operator<<(ostream &out,Person ob){
    out<> 输入运算符
istream& operator>>(istream &in,Person &ob){
    in>>ob.num>>ob.name>>ob.score;
    return in;
}
//全局函数重载+运算符
Person operator+(Person &ob1,Person &ob2){
    Person tmp;
    tmp.num   = ob1.num+ob2.num;
    tmp.name  = ob1.name+ob2.name;
    tmp.score = ob1.score+ob2.score;
    return tmp;
}
int main()
{
    Person Jery{101,"Jery",99.9f};
    Person Tom{102,"Tom",98.9f};

    cout<

9.13.6 重载+运算符(成员函数实现推荐)

【带头学C++】----- 九、类和对象 ---- 9.13 运算符重载——(9.13.5-9.13.6)_第4张图片

【带头学C++】----- 九、类和对象 ---- 9.13 运算符重载——(9.13.5-9.13.6)_第5张图片

代码:

#include 
#include 
#include "array.h"

using namespace std;
class Person
{
    friend ostream& operator<<(ostream &out,Person ob);
    friend istream& operator>>(istream &in,Person &ob);
    //friend Person operator+(Person &ob1,Person &ob2);
private:
    int num;
    string name;
    float score;
public:
    Person(){}
    Person(int num,string name,float score):num(num),name(name),score(score){}
    //成员函数实现重载加法运算符
    Person operator+(Person &ob)
    {
        Person tmp;
        tmp.num = num + ob.num;
        tmp.name = name + ob.name;
        tmp.score = score + ob.score;
        return tmp;
    }

};
//全局函数重载operator<< 输出运算符
ostream& operator<<(ostream &out,Person ob){
    out<> 输入运算符
istream& operator>>(istream &in,Person &ob){
    in>>ob.num>>ob.name>>ob.score;
    return in;
}
int main()
{
    Person Jery{101,"Jery",99.9f};
    Person Tom{102,"Tom",98.9f};

    //Jery + Tom  ==> Jery.operator+(Tom)


    //cout<

点赞  + 收藏 + 关注

❤️您的支持❤️是我最大的动力❤️相互学习❤️共同进步❤️一起搞钱❤️动动发财的小手❤️

  ⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️十星好评,Erike的专用模板⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️ 

什  么 ?您  要  打  赏 ?谢    谢    老   板!老    板    大    气! 
 

你可能感兴趣的:(C++从基础到抗大旗,c++,开发语言,链表,算法,学习)