I have always thought that the final keyword of Java is similar to the const keyword of C ++. Through more in-depth study of C ++, I gradually learned some of their differences.
1. The final of Java can modify the class. Although the const of C ++ can also be written in front of the class, it does not seem to work (not very sure)
2. c ++ protects const-modified class objects better than Java's final
Java:
Final classa A = new classa ();
A = B; // error: the constant cannot be modified on the left.
A. setvalue (10); // OK: it is acceptable to modify the member variables of object A. This is not very consistent with the original intention of using final.
A. getvalue (); // OK
C ++:
Const classc C ();
Classc D ();
C = D; // error: the constant cannot be modified on the left.
C. setvalue (10); // error: the setvalue method must be const, And the setvalue method cannot modify the member variables of Object C.
D. setvalue (10); // OK: whether the setvalue method is const or not, and the setvalue method can modify the member variables of Object D.
PS: classa and classc are Java and C ++ classes respectively. A, B, C, and D are class objects, and the setvalue method is used to change a member variable of these class objects.
The above shows that C ++ConstClass object,You can only call its constMethod,And the constThe method cannot modify member variables,This constThe method can beNon-constClass Object call.
A. setvalue (10) can be executed, while running C. setvalue (10) is incorrect. For a pair of comparisons, we can see that C ++ is better at protecting constant class objects than Java.
In the C ++ class, methods like getvalue can be modified with const, and inline is better.