C++之运算符重载(一)

一 . “+”(加号)运算符重载

//重载 + 运算符

#include <iostream>
using namespace std;

class Person
{
    friend Person operator+(Person &p1,Person &p2);
private:
    int age;
public:
    Person(){}

    void setAge(int n)
    {
        age = n;
    }
    void showAge()
    {
        cout<<age<<endl;
    }
    
//    //成员函数实现重载
//    Person operator+(Person &p)
//    {
//        Person temp;
//        temp.age = this->age + p.age;
//        return temp;
//    }
};

//全局函数实现重载
Person operator+(Person &p1,Person &p2){
    Person temp;
    temp.age = p1.age + p2.age;
    return temp;

}

int main(){
    Person p1;
    p1.setAge(1);
    Person p2;
    p2.setAge(2);
    Person p3 = p1 + p2;
    p3.showAge();
}

二. “<<”(左移)运算符重载

//重载 <<	(左移) 运算符
#include <iostream>
using namespace std;

class Man
{
    friend ostream & operator<<(ostream &cout,Man &m);
private:
    string m_name;
    int m_age;
public:
    Man(string name,int age){
        this->m_name = name;
        this->m_age = age;
    }
};

//全局函数实现重载
ostream & operator<<(ostream &cout,Man &m)
{
    cout<<"My name is : "<<m.m_name<<endl;
    cout<<"My age is : "<<m.m_age<<endl;
    return cout;
}


int main(){
    Man man("Tom",11);
    cout<<man<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值