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
    //

  • 相关阅读:
    【数论】 快速幂
    【时间复杂度】你还在担心时间复杂度太高吗?
    【数据结构】 最小生成树(三)——prim算法
    【数据结构】 最小生成树(二)——kruskal算法
    node.js初识11
    node.js初识10
    node.js初识09
    node.js初识08
    node.js初识07
    node.js初识06
  • 原文地址:https://www.cnblogs.com/sysnap/p/3439843.html
Copyright © 2011-2022 走看看