• 理解运算符重载 4


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


    /*
    重载运算符,选择成员还是非成员实现?
    1 赋值(=), 下标([]), 调用(()), 成员访问箭头(->)操作符必须定义为成员
    2 复合赋值操作符( +=, -=, *=, =, %=, &=, ^=, |= , <<=, >>=) 一般定义为类的成员,但不是必须这么做,也可以定义为非成员
    3 自增,(++),自减(--)和解引用(*)一般会定义为类成员
    4 算术运算符(+, -, *, /, %, ),相等操作符( == ),关系操作符(>, < , >=, <=,),位操作符(&, ^, |, !),一般定义为非成员实现。
    */

    namespace operator_test
    {

    class CObject
    {
    friend std::ostream& operator<<(std::ostream& out, const CObject& obj);
    public:
    CObject(int a) : m_a(a)
    {

    }

    int Get()
    {
    return m_a;
    }

    CObject& operator=(CObject& obj)
    {
    this->m_a = obj.Get();
    return *this; //赋值运算符重载必须返回 *this
    }

    CObject& operator=(int obj)
    {
    this->m_a = obj;
    return *this; //赋值运算符重载必须返回 *this
    }

    CObject& operator++()
    {
    this->m_a++;
    return *this;
    }

    CObject operator++(int)
    {
    //
    //因为是后缀,所以必须要返回一个副本
    //
    CObject newObj = CObject(this->m_a);
    this->m_a++;
    return newObj;
    }

    private:
    int m_a;
    };

    CObject operator+(CObject& obj1, CObject& obj2)
    {
    return CObject(obj1.Get() + obj2.Get());
    }

    CObject operator*(CObject& obj1, CObject& obj2)
    {
    return CObject(obj1.Get()*obj2.Get());
    }

    bool operator==(CObject& obj1, CObject& obj2)
    {
    return (obj1.Get() == obj2.Get());
    }
    bool operator!=(CObject& obj1, CObject& obj2)
    {
    return !(obj1.Get() == obj2.Get());
    }

    std::ostream& operator<<(std::ostream& out, const CObject& obj)
    {
    out << obj.m_a;
    return out;
    }
    }

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

    //
    //重载算术运算符
    //
    operator_test::CObject add = obj1 + obj2;
    std::cout << add << std::endl;

    operator_test::CObject muil = obj1*obj2;
    std::cout << muil << std::endl;

    //
    //重载相等运算符
    //
    if(obj1 == obj2)
    {
    std::cout << "obj1 == obj2" << std::endl;
    }else
    {
    std::cout << "obj1 != obj2" << std::endl;
    }

    //
    //重载赋值操作符.
    //
    operator_test::CObject newObject = obj1;
    std::cout << newObject << std::endl;

    //
    //自增操作符++( 自减原理一样 )重载
    //
    std::cout << newObject++ << std::endl;
    std::cout << newObject << std::endl;

    newObject = 10;
    std::cout << ++newObject << std::endl;

    std::cout << "---------------------------" << std::endl;

    }

  • 相关阅读:
    vue 保留两位小数 不能直接用toFixed(2) ?
    分页导航 简洁版 只有上一页下一页
    vue style width a href动态拼接问题 ?
    使用html元素的getBoundingClientRect来获取dom元素的时时位置和大小
    javascript中函数的闭包自调用
    javascript中的Promise使用
    常用css样式颜色值: 64位真彩和256位值
    javascript数组Array强大的splice()方法
    Bootatrap常用样式
    angularjs上传图片和文件
  • 原文地址:https://www.cnblogs.com/sysnap/p/3440048.html
Copyright © 2020-2023  润新知