理解运算符重载 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;

}

原文地址:https://www.cnblogs.com/sysnap/p/3440048.html