Here's a question first:
Problem Description : the function int Getvertexcount (SHAPE * b) calculates the number of vertices of B, if B points to the Shape type, the return value is 0, if B points to the triangle type, the return value is 3, and if B points to the rectangle type, The return value is 4.
Of these, triangle and rectangle are inherited from the shape class.
The main function of this problem is defined as follows:
int main () { Shape s; cout << Getvertexcount (&s) << Endl; Triangle T; cout << Getvertexcount (&t) << Endl; Rectangle R; cout << Getvertexcount (&r) << Endl;}
Analysis: First of all, the problem is similar to the reflection mechanism in Java and C #, here we consider using the dynamic_cast function, for usage, let's look at a function first:
A is B ' s fathervoid my_function (A * my_a) { b* my_b = dynamic_cast<b*> (my_a); if (my_b! = nullptr) My_b->methodspecifictob (); else std::cerr << " Object is not B type" << Std::endl;}
As long as the object pointer is nullptr to determine which class the object runs, the full code is as follows:
#include <cstdio> #include <cstring> #include <iostream>using namespace Std;class shape{public:shape () {}virtual ~shape () {}};class triangle:public shape{public:triangle () {}~triangle () {}};class rectangle:public Shape {Public:rectangle () {}~rectangle () {}};/*) completes the function with the dynamic_cast type conversion operator to calculate the number of vertices of B, if B points to the shape type, the return value is 0, and if B points to the triangle type, The return value is 3, and if B points to the rectangle type, the return value is 4. */int Getvertexcount (Shape * b) {triangle* my_triangle = dynamic_cast<triangle*> (b); if (my_triangle! = nullptr) {// Description is Trianglereturn 3;} rectangle* My_rectangle = dynamic_cast<rectangle*> (b), if (my_rectangle! = nullptr) {//description is Rectanglereturn 4;} return 0;} int main () {Shape s;cout << getvertexcount (&s) << Endl; Triangle t;cout << getvertexcount (&t) << Endl; Rectangle r;cout << getvertexcount (&r) << Endl;}
Dynamic judgment function of polymorphism based on C + +