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

  • 相关阅读:
    srvany.exe和instsrv.exe_2
    srvany.exe和instsrv.exe
    C# “国密加密算法”SM系列的C#实现方法
    DMZ讲解
    java 判断字符串是否为json格式
    MFC DrawText如何使多行文字居中显示 Demo
    C++ 实现一个日志类
    数据库两个神器【索引和锁】
    CentOS 7.*编译安装PHP8
    Centos添加永久环境变量
  • 原文地址:https://www.cnblogs.com/sysnap/p/3439843.html
Copyright © 2011-2022 走看看