I. Pre-operator and the operator post
Q: The following code there is no difference? why?
Code implementation
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i = 0;
i++;
++i;
return 0;
}
Unexpected fact
1. modern compilers optimize the code will
2. optimized such that the final binary more efficient
3. optimized missing binary C / C ++ native semantic
4. impossible to restore from the binary program compiled C / C ++ program
Q: ++ operator can override it? How to distinguish between the front and rear + + + +?
++ operator can be overloaded
globally member function can be any function overloading
2. Pre ++ overload operators do not require additional parameters
3. Overload operator needs post ++ type int parameter placeholder
code sample
#include <iostream>
#include <string>
using namespace std;
class Test
{
int mValue;
public:
Test(int i)
{
mValue = i;
}
int value()
{
return mValue;
}
Test& operator ++ ()//前置操作符
{
++mValue;
return *this;
}
Test operator ++ (int)//后置操作符
{
Test ret(mValue);//当前对象的值保存在一个对象中
mValue++;
return ret;
}
};
int main()
{
Test t(0);
cout<<t.value()<<endl;
++t;
cout<<t.value()<<endl;
return 0;
}
Pre-operator operation and operators results shown in Figure rear
of the sample code can be seen that the front and rear operator is the operator there is a difference of
1 for a base type is. - Pre ++ ++ efficiency and the efficiency of the post is substantially the same, rotates according to the coding standard item group
2. for the type of object classes - pre post ++ ++ higher efficiency, mainly because there is no pre-operator call constructor, so try to use the front ++ when using the program to improve efficiency