#include<iostream>
using namespace std;
//递增运算符重载
//int a=10;cout<<a++<<endl;->10 ;cout<<a<<endl; ->11;
//int b=10;cout<<++b<<endl;->11;cout<<b<<endl;->11;
//
class MyInteger
{
friend ostream& operator<<(ostream& cout, MyInteger myint);
public:
MyInteger()//在构造函数中初始化成员
{
m_num = 0;
}
//重载前置++运算符
MyInteger operator++()//返回引用时为了一直对一个数据进行操作
{
m_num++;
return *this;//this是指向自身的指针,*this就是解引用自身
}
//重载后置++运算符
private:
int m_num;
};
//重载左移运算符<<:为了左移运算符在左边,所以重载要要在全局函数中
ostream& operator<<(ostream& cout, MyInteger myint)
{
cout << myint.m_num;
return cout;
}
void test01()
{
MyInteger myint;
cout <<++ (++myint) << endl;
cout << myint << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
#include<iostream>
using namespace std;
//递增运算符重载
//int a=10;cout<<a++<<endl;->10 ;cout<<a<<endl; ->11;
//int b=10;cout<<++b<<endl;->11;cout<<b<<endl;->11;
//
class MyInteger
{
friend ostream& operator<<(ostream& cout, MyInteger myint);
public:
MyInteger()//在构造函数中初始化成员
{
m_num = 0;
}
//重载前置++运算符
MyInteger& operator++()//返回引用时为了一直对一个数据进行操作
{
//先进行++操作
m_num++;
//后返回自身
return *this;//this是指向自身的指针,*this就是解引用自身
}
//重载后置++运算符
MyInteger operator++(int)//这里的int时占位参数,可以区分前置和后置递增
{//不能返回temp的引用,因为tmp是一个局部数据,局部对象在当前数据执行完后就被释放掉了,如果还要返回引用就是非法操作了
//先返回自身 ->记录自身及结果
MyInteger temp = *this;
//后进行++操作
m_num++;
//将记录的结果返回
return temp;
}
private:
int m_num;
};
//重载左移运算符<<:为了左移运算符在左边,所以重载要要在全局函数中
ostream& operator<<(ostream& cout, MyInteger myint)
{
cout << myint.m_num;
return cout;
}
void test01()
{
MyInteger myint;
cout <<++ (++myint) << endl;
cout << myint << endl;
}
void test02()
{
MyInteger myint;
cout << myint++ << endl;
cout << myint << endl;
}
int main()
{
test01();
test02();
system("pause");
return 0;
}