In Java, if a is a base class and B is a derived class, then instanceof can be used to determine whether an instance object is a or B, which is equivalent to a two-dollar operator, but with the = =, A, <, the difference is that it is made up of letters and is a reserved word for Java. But in C + + there is no such keyword, but we can use dynamic_cast to achieve the same functionality, see the following code:
Java ' instanceof '
//Java ' instanceof ' Public classA {// ...} Public classBextendsA {// ...} Public classCextendsA {// ...} Public voidprocess (a a) {if(AinstanceofB) {//Process B } if(a instanceof C) {//Process C }}
C + + ' dynamic_cast '
//C + + ' dynamic_cast 'classA {// ...}classB: PublicA {// ...}classC: PublicA {// ...}voidProcess (A *a) {if(B *b = dynamic_cast<b*>(a)) {//Process B } if(C *c = dynamic_cast<c*>(a)) {//Process C }}
C + + ' dynamic_cast ' and Java ' instanceof ' usage comparison