// Operator.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Integer
{
public:
//explicit如果添加explicit就不能进行隐式构造
//隐式构造不会导致拷贝构造函数调用
Integer(int num):m_num(num)
{
}
//覆盖了拷贝构造函数就必须对拷贝对象的成员进行值赋值 有必要的时候还要进行深层拷贝比如重新分配内存
Integer(const Integer&integer)
{
m_num=integer.m_num;
cout<<"CPY CONSTRUCTION FUNCTION CALLED"<<endl;
}
//后缀形式
//如果后缀形式那么形参会是0
void operator++(int i)
{
this->m_num=m_num+1;
}
//前缀形式
void operator++()
{
this->m_num++;
}
//前置--
void operator--()
{
this->m_num--;
}
//后缀形式
void operator--(int i)
{
this->m_num=m_num-1;
}
//重载+ 如果接受的不是 Integer&integerRef那么依然会触发拷贝构造函数
Integer operator+(Integer &integerRef)
{
return Integer(m_num+integerRef.m_num);
}
Integer operator+(int i)
{
return m_num+i;
}
Integer operator-(int i)
{
return m_num-i;
}
//重载=
void operator=(int i)
{
m_num=i;
}
//重载+= -=
void operator+=(int i)
{
m_num+=i;
}
void operator-=(int i)
{
m_num-=i;
}
//返回值
int ToVal()
{
return m_num;
}
//函数返回 赋值会导致拷贝构造调用
Integer GetObj()
{
return *this;
}
//转换成字符串
const string ToString()
{
char buf[10]="";
_itoa_s(m_num,buf,10);
return string(buf) ;
}
//COPY MYSELF
//只有返回新的对象 或者创建新的对象通过其他对象初始化的时候 才会触发拷贝构造 或者函数体内部创建一个对象并且把对象作为返回值 才会触发 拷贝构造函数调用
//如果return Integer(m_num);是不会触发拷贝构造的
//仿函数
Integer operator()()
{
return *this;
}
//重载 对于ios流类库的 标准输入 标准输出 标准错误输出 所以我们只能声明<< >>插入提取运算符为 友元函数
friend istream& operator >>(istream&is,Integer&intObj);
friend ostream& operator <<(ostream&os,Integer&intObj);
//从对象提取数据到变量 << >>运算符重载
void operator>>(int &i)
{
i=m_num;
}
//输出到对象
void operator<<(int i)
{
m_num=i;
}
private:
int m_num;
protected:
};
//重载IO
istream& operator >>(istream&is,Integer&intObj)
{
is>>intObj.m_num;
return is;
}
ostream& operator <<(ostream&os,Integer&intObj)
{
os<<intObj.m_num ;
return os;
}
int _tmain(int argc, _TCHAR* argv[])
{
//implicit
Integer integerObj1=1;
Integer integerObj2=2;
//integerObj1=integerObj2; 不会触发拷贝构造函数 Integer obj=integerObj1 才会触发拷贝构造调用
//相当于integerObj++0
integerObj1++;
//相当于++x
++integerObj1;
cout<<"integerObj1="<<integerObj1.ToVal()<<endl;
Integer intObjCmb=integerObj1+integerObj2;
cout<<"intObjCmb="<<intObjCmb.ToVal()<<endl;
Integer w=integerObj1;
cout<<"w="<<w.ToString()<<endl;
w+=2 ;
cout<<"w+2="<<w.ToString()<<endl;
cout<<"Copy W="<<w().ToString()<<endl;
//重载标准输入和输出.....
w=125;
cout<<"W="<<w<<endl;
int i;
w>>i ;
cout<<"i=w="<<w<<endl ;
w<<1000;
cout<<"w="<<w<<endl ;
w>>i ;
cout<<"i=w="<<w<<endl ;
return 0;
}