C++中一共有两种自增运算符
1、前置自增运算符
2、后置自增运算符
前置自增运算符可以链式使用,而后置自增运算符不可以链式使用
1、重载前置运算符
by 成员函数的方式
#include <iostream>
using namespace std;
class Student{
public:
int m_age;
double m_score;
Student(){
m_age = 19;
m_score = 100.0;
}
Student(const Student& stu){
m_age = stu.m_age;
m_score = stu.m_score;
}
Student& operator++(){ // 这里一定要是返回对象的引用 否则链式使用的时候会出问题
(this->m_age)++;
(this->m_score)++;
return *this;
}
};
ostream& operator<<(ostream& os,const Student& stu){
os << "m_age = " << stu.m_age << endl;
os << "m_soce = " << stu.m_score << endl;
return os;
}
istream& operator>>(istream& is,Student& stu){
cout << "m_age: ";
is >> stu.m_age;
cout << "m_score: ";
is >> stu.m_score;
return is;
}
void test1(){
Student stu;
cin >> stu;
cout << stu;
cout << ++stu << endl;
cout << ++(++stu) << endl; // 可以像这个样子链式使用前置自增
return;
}
int main(){
test1();
system("pause");
return 0;
}
虽然链式使用了两次自增运算符,但是实际上数据只自增了一次。
原因: 第二次自增的时候,系统重新构造出了一个数据相同的对象。因此,重载前置运算符的时候的返回值一定是对象的引用。
2、重载后置运算符
by 成员函数
#include <iostream>
using namespace std;
class Student{
public:
int m_age;
double m_score;
Student(){
m_age = 19;
m_score = 100.0;
}
Student(const Student& stu){
m_age = stu.m_age;
m_score = stu.m_score;
}
Student& operator++(){
(this->m_age)++;
(this->m_score)++;
return *this;
}
Student operator++(int){
Student tempStudent(*this);
m_age ++;
m_score ++;
return tempStudent;
}
};
ostream& operator<<(ostream& os,const Student& stu){ //重载左移运算符
os << "m_age = " << stu.m_age << endl;
os << "m_soce = " << stu.m_score << endl;
return os;
}
istream& operator>>(istream& is,Student& stu){ // 重载右移运算符
cout << "m_age: ";
is >> stu.m_age;
cout << "m_score: ";
is >> stu.m_score;
return is;
}
void test1(){
//Student stu = *(new Student()); 该方法可以将数据开辟到堆区
Student stu; // 默认构造函数创建对象
cout << stu << endl;
cout << (stu++) << endl;
//cout << (stu++)++ << endl; // 是不允许这样的操作的。
cout << stu << endl;
return;
}
int main(){
test1();
system("pause");
return 0;
}