类和对象–C++运算符重载
C++ 预定义的运算符,只能用于基本数据类型的运算,不能用于对象的运算
如何使运算符能用于对象之间的运算呢
递增运算符重载
递增和递减一般是改变对象的状态,所以一般是重载为成员函数
1.前置递增
#include <iostream>
using namespace std;
class MyInteger{
friend ostream& operator<<(ostream& out, MyInteger myint);//友元函数,使类外的可以访问私有属性
public:
MyInteger(){
m_Num = 0;
}
MyInteger& operator++(){//解引用
m_Num++;//先++
return *this;//再返回
}
private:
int m_Num;
};
ostream& operator<<(ostream& out, MyInteger myint) {
out << myint.m_Num;
return out;
}
void test() {//前置递增 先++ 再返回
MyInteger myInt;
cout << ++myInt << endl;
cout << myInt << endl;
}
int main() {
test();
system("pause");
return 0;
}
2.后置递增
#include <iostream>
using namespace std;
class MyInteger{
friend ostream& operator<<(ostream& out, MyInteger myint);//友元函数,使类外的可以访问私有属性
public:
MyInteger(){
m_Num = 0;
}
MyInteger operator++(int) {
//先返回
MyInteger temp = *this; //记录当前本身的值,然后让本身的值加1,但是返回的是以前的值,达到先返回后++
m_Num++;
return temp;
}
private:
int m_Num;
};
ostream& operator<<(ostream& out, MyInteger myint) {
out << myint.m_Num;
return out;
}
void test() {//后置++ 先返回 再++
MyInteger myInt;
cout << myInt++ << endl;
cout << myInt << endl;
}
int main() {
test();
system("pause");
return 0;
}
注意:
返回引用是为了始终对一个对象进行操作,保证链式编程思想
区分前置和后置用占位参数int,其他的不行
前置:MyInteger &operator++{ }
后置:MyInteger operator++(int) { }
后置递增不能使用引用的原因:使用完会被释放掉,不能返回局部地址,这是非法操作