运算符重载实战

1.成员函数重载

2.全局函数重载

3.输出运算符重载

4.拷贝赋值运算符

5.移动赋值运算符

#include <iostream>
#include <string>

using namespace std;

/* 
 * 1.成员函数重载
 * 2.全局函数重载
 * 3.输出运算符重载
 * 4.拷贝赋值运算符
 * 5.移动赋值运算符
 * */

class stu{
public:
    string name;
    int age;
    stu(int age):age(age){
        cout << "有参构造stu"<< endl;
    }

    stu(string name,int age):name(name),age(age){
        cout << "有参构造2stu"<< endl;
    }

    stu operator+(stu &s){
        return (this->age + s.age);
    }
};

class teacher{
public:
    string name;
    int age;

    teacher(int age):age(age){
        cout << "有参构造1"<< endl;
    }

    teacher(string name,int age):name(name),age(age){
        cout << "有参构造2"<< endl;
    }
};

teacher operator+ (teacher & te,teacher & t){
    return (te.age + t.age);
}

class school{
public:
    string name{"希望小学"};
    school(string name){
        this->name = name;
    }
};

ostream& operator<<(ostream& o,school& s){
    o << s.name;
    return o;

}

class hospital{
public:
    string address;
    hospital(){
        cout << "hostpital无参构造"<< endl;
    }
};

istream& operator>>(istream &in,hospital &h){
    in >> h.address;
    return in;
}

class hotel{
public:
    string name;
    int price;

//    hotel(string name,int price){
//        this->name = name;
//        this->price = price;
//    }

    hotel& operator=(const hotel &p){
        cout << "执行拷贝赋值函数"<< endl;
        this->name = p.name;
        this->price = p.price;
        return *this;
    }

};

class doctor{
public:
    string name;
    int age;

    doctor& operator=(doctor && d){
        cout << "调用移动赋值运算函数"<< endl;
        if(this != &d){
            this->name = move(d.name);
            d.name = " ";
            this->age = move(d.age);
            d.age = 0;
        }
        return *this;
    }
};

int main() {
    stu s1("小明",12);
    stu s2("小红",13);
    stu s3 = s1 + s2;
    cout << s3.age << endl;

    teacher t1("夏老师",30);
    teacher t2("王老师",32);
    teacher t3 = t1 + t2;
    cout << t3.age << endl;

    school sc("希望中学");
    cout << sc << endl;

    hospital h;
    cin >> h;
    cout << h.address << endl;

    hotel p;
    p.name = "京基酒店";
    p.price = 100;
    hotel p2;
    p2 = p;

    doctor d;
    d.name = "牙博士";
    d.age = 18;
    doctor d2;
    d2 = move(d);

    return 0;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值