C++ operator 加法和<<

#include <iostream>
#include <string>
using namespace std;
/*
    运算符重载:对已经有的运算符重新定义,赋予其另外一种功能,用来适用于不同的数据类型
*/

// 加号运算符重载
class Person
{
public:
    // 成员函数重载
    // Person operator+(Person &p)
    // {
    //     Person temp;
    //     temp.a = this->a + p.a;
    //     temp.b = this->b + p.b;
    //     return temp;
    // }

public:
    int a;
    int b;
};
// 成员运算符重载+号

// 全局函数重载+号
Person operator+(Person &A, Person &B)
{
    Person temp;
    temp.a = A.a + B.a;
    temp.b = A.b + B.b;
    return temp;
}

// 全局函数重载
Person operator+(Person &A, int a)
{
    Person temp;
    temp.a = A.a + a;
    return temp;
}

void test()
{
    Person p1;
    p1.a = 10;
    p1.b = 20;
    Person p2;
    p2.a = 30;
    p2.b = 40;
    // 成员函数重载的本质
    // Person p3 = p1.operator(p2);

    // 全局函数的本质调用
    // Person p3 = operatot+(p1, p2)

    // 二者简化
    Person p3 = p1 + p2;
    Person p4 = p1 + 100; // 100是常量 不可以用引用
    cout << p3.a << "\t" << p3.b << endl;
    cout << p4.a << endl;
}

// 左移运算符 作用可以输出自己定义的数据类型
class X
{
    //  public:
    //  利用成员函数重载 左移运算符 p.operator<<(cout) 简化版本 p << cout
    //  void operator<<(cout)
    //  {}
    //  不会利用成员函数重载<<运算符,因为无法实现cout在左侧

    friend ostream &operator<<(ostream &cout, X &p);

public:
    X(int a, int b)
    {
        this->a = a;
        this->b = b;
    }

private:
    int a;
    int b;
};

// 全局函数重载左移运算符 cout全局只能有一个 流对象只能引用不能赋值
ostream &operator<<(ostream &cout, X &p) // 本质 operator<< (cout, p) 简化cout << p
{
    cout << p.a << " " << p.b;
    return cout; // 返回的是一个标准的输出流对象
}

void testx()
{
    X x(12563, 4848);
    cout << x << endl; // 此时cout << x 返回的是一个ostream cout, 可以后面继续<< endl
}

int main()
{
    // test();
    testx();
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值