3.1 自己实现int类型 MyInteger
3.2 内部维护以int数据
3.3 MyInteger myInt
3.4 myInt ++ 后置 ++myInt 前置
3.5 重载++运算符 operator++() 前置 operator++(int) 后置
3.6 前置理念 先++ 后返回自身 后置理念 先保存住原有值 内部++ 返回临时数据
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
#if(1)
class Nick {
public:
//friend ostream& operator<<(ostream &cout, Nick &nick);
friend ostream& operator<<(ostream &cout, Nick nick);
Nick(int val) :m_val(val) {};
Nick() {
m_val = 0;
}
//前置++重载
Nick& operator++() {
this->m_val++;
return *this;
}
//后置++重载
Nick operator++(int) {
//先保存目前数据
Nick temp = *this;
m_val++;
return temp;
}
private:
int m_val;
};
ostream& operator<<(ostream &cout, Nick nick)
//ostream& operator<<(ostream &cout, Nick &nick)
{
cout << nick.m_val;
return cout;
}
void test01() {
Nick nick1(32);
Nick nick2;
cout << "++nick1 = " << ++nick1 << endl;
cout << "nick2++ = " << nick2++ << endl;//报错:二进制“<<”: 没有找到接受“MyInteger”类型的右操作数的运算符(或没有可接受的转换)
//C2679 binary '<<': no operator found which takes a right - hand operand of type 'MyInteger' (or there is no acceptable conversion)
/*
解决方法:
1)后缀++返回的是值而不是引用,<<运算符的重载只接受引用类型的参数,因此要进行强制类型转换
2)将<<运算符重载时第二个参数由引用改为值
*/
//cout << "nick2++ = " << (Nick&)nick2++ << endl;
cout << "nick1 = " << nick1 << endl;
}
int main(){
test01();
system("pause");
return 0;
}
#endif