A ++ B, anb
One of my questions:First, let's take a look at the function implementation of the following class. ++ indicates that each bit of the class's data is + 1. If it is not carried, an integer (the processed data) is returned ), + indicates the addition of two classes. each bit of the class is added, and the result is an integer. Code implementation: testmain. cpp:
#include <iostream>#include "strange_plus.h"using namespace std;int main() { integer a, b; int t1, t2, ans; t1 = a + b; t2 = ++a; cout << t1 << endl; cout << t2 << endl; ans = a+(++b); cout << ans << endl; return 0;}
Strange_plus.h:
#include <string.h>class integer { public: integer() { data = 1; } ~integer() {} friend int operator + (const integer i1, const integer i2) { int temp1 = i1.data; int temp2 = i2.data; int temp3 = 0; int ans = 0; while (temp1 || temp2) { temp3 = temp3 * 10 + ((temp1 % 10 + temp2 % 10) % 10); temp1 /= 10; temp2 /= 10; } while (temp3) { ans = ans * 10 + temp3 % 10; temp3 /= 10; } return ans; } int operator ++ () { int temp[10]; memset(temp, 0, sizeof(temp)); int temp_int = data; int i = 0; while (temp_int) { temp[i++] = temp_int % 10; temp_int /= 10; } for (int j = 0; j < i; j++) { temp[j] = (temp[j] + 1) % 10; } int ans = 0; for (int j = i - 1; j >= 0; j--) { ans = ans * 10 + temp[j]; } data = ans; return ans; } private: int data;};
Then an error is reported. Check the error message:
I don't know much about it, but I found it quite strange. If I add this: integer (int temp) {data = temp;} In strange_plus.h, I can run it:
The analysis is as follows: first, for a + (++ B), calculate ++ B and return an integer. For this integer, it cannot be added to the class, after adding the code integer (int temp) {data = temp;}, you can convert the integer into a class and add it together;
In fact, this phenomenon is the static binding rule of the function, as mentioned earlier:
Here is the third step. In this case, the constructor integer (int temp) {data = temp;} is equivalent to forced conversion. Similarly, if ++ is changed to the Postfix, a + (++ B) is changed to a ++ B. Note the priority: the front-end ++> front-end ++ has the same priority as the front-end ++, but is lower than the back-end ++.