zoukankan      html  css  js  c++  java
  • 理解运算符重载 1

    #include "stdafx.h"
    #include <iostream>

    //
    //函数重载
    //

    namespace operator_test
    {
    //
    //先定义一个类
    //
    class CObject
    {
    public:
    CObject(int a) : m_a(a)
    {

    }

    int Get()
    {
    return m_a;
    }

    int Add(CObject& obj2)
    {
    return (this->Get() + obj2.Get());
    }

    int operator+(CObject& obj2)
    {
    return (this->Get() + obj2.Get());
    }
    private:
    int m_a;
    };

    int Add(CObject& obj1, CObject& Obj2)
    {
    return (obj1.Get() + Obj2.Get());
    }

    //int operator+(CObject& obj1, CObject& Obj2)
    //{
    // return (obj1.Get() + Obj2.Get());
    //}
    }

    void test_operator_test()
    {
    operator_test::CObject obj1(10);
    operator_test::CObject obj2(20);

    //
    //1 把obj1 和 obj2相加,相加后的值. 通过一个全局函数来实现
    //
    std::cout << operator_test::Add(obj1, obj2) << std::endl;

    //
    //1 把obj1 和 obj2相加,相加后的值. 通过CObject一个函数来实现
    //
    std::cout << obj1.Add(obj2) << std::endl;

    //
    //1 把obj1 和 obj2相加,相加后的值. 把obj1.Add变得更可读
    //
    std::cout << (obj1 + obj2) << std::endl;
    std::cout << obj1.operator+(obj2) << std::endl; //跟上面语句是等价的.

    //
    //所以std::cout也可以写成下面的样子
    //
    std::cout.operator<<(obj1.operator+(obj2))<< std::endl;
    }


    //
    //双目运算符,类成员情况下。classobject1.operator x (classobject2) 等价于 classobject1 x classobject2
    //

  • 相关阅读:
    [BZOJ3257]树的难题
    [BZOJ4987]Tree
    [NOI2015][洛谷P2150]寿司晚宴
    P2221 [HAOI2012]高速公路
    BUG全集(我遇到的)
    NOIP2018游记
    BZOJ1103
    Google Chrome 优化
    特殊空格
    Ant Design Vue 使用
  • 原文地址:https://www.cnblogs.com/sysnap/p/3439843.html
Copyright © 2011-2022 走看看