后置运算符的特性
code:
#include
using namespace std;
class Horse
{
friend void test01();
private:
int m_age = 3;
public:
Horse(int age)
{
m_age = age;
}
Horse& operator++() // 必须要返回引用,因为这样才是对原对象的不断累加,才会实现原对象值夜随之改变
{
m_age ++;
return *this;
}
};
void test01()
{
Horse h1(0);
cout << "age: " << h1.m_age << endl;
cout << "age: " << (++(++(++h1))).m_age << endl;
cout << "age: " << h1.m_age << endl;
}
int main()
{
int a1 = 0;
cout << ++(++a1) << endl;
test01();
system("pause");
return 0;
}
result:
2
age: 0
age: 3
age: 3
code:
#include
using namespace std;
class Horse
{
friend void test01();
friend void test02();
private:
int m_age = 3;
public:
Horse(int age)
{
m_age = age;
}
Horse& operator++() // 必须要返回引用,因为这样才是对原对象的不断累加,才会实现原对象值夜随之改变
{
m_age ++;
return *this;
}
Horse operator++(int) // 必须要利用占位参数来区分为后置,这里先要将当前的对象属性记录下来,最后返回,因为后置++是先返回本身值,再进行+1操作
{
Horse result = *this;
m_age++;
return result; // 不能返回局部变量的引用,所以函数的返回值是变量本身
}
};
void test01()
{
Horse h1(0);
cout << "age: " << ++(++(++h1)).m_age << endl; //先对操作数进行累加,再返回
cout << "age: " << h1.m_age << endl;
}
void test02()
{
Horse h1(0);
cout << "age: " << h1.m_age << endl;
cout << "age: " << h1++.m_age << endl;
cout << "age: " << h1.m_age << endl;
}
int main()
{
int a1 = 0;
cout << ++(++a1) << endl;
test01();
int b1 = 0;
cout << b1++ << endl;
cout << b1 << endl;
//cout << (b1++)++ << endl; //错误语句,后置的自增是无法嵌套的
test02();
system("pause");
return 0;
}
result:
2
age: 3
age: 3
0
1
age: 0
age: 0
age: 1