Connect the book ......
I just wanted to read the book, but I recently read the design patterns and Objective C ++ books, which will be encapsulated in many c ++ books, because of inheritance and polymorphism, you have to take notes.
For virtual functions, in polymorphism, you must set the destructor of the base class as virtual functions and implement them, in the reverse order of Object Construction. Otherwise, only the part of the base class is parsed, the part of the derived class cannot be analyzed successfully.
class shape{public:shape(){};virtual void draw() = 0;virtual ~shape(){cout << "shape destruction" << endl;}};class rectangle : public shape{public:rectangle(){};void draw(){}~rectangle(){cout << "rectangle destruction" << endl;}};class round : public shape{public:round(){};void draw(){}~round(){cout << "round destruction" << endl;}};void main(){shape * s;
s = new rectangle();s->draw();delete s;s = new round();s->draw();delete s;}
§ Pure virtual functions
In the example of shape in the virtual function, there is a draw function, but if it is implemented, draw shape? This implementation is very vague. If we instantiate the shape base class, we will not be able to figure out what draw is (drawing messy things, this is not what the customer needs, the customer needs a specific image ). Therefore, it is necessary to remove the draw definition (Implementation) from the base class shape, and leave its definition (Implementation) to the derived class.
Class shape {public: shape () {}; virtual void draw () = 0; // pure virtual function}; Class rectangle: Public shape {public: rectangle (){}; void draw () {draw a square; }}; class round: Public shape {public: round () {}; void draw () {draw a circle; }}; void main () {shape * s; S = new rectangle (); s-> draw (); s = new round (); s-> draw ();}
§ Summary
Check whether the above code is very touched. recall it. The abstract class in C ++ is similar to the interface in Java, but the C ++ abstract class allows the appearance of member variables. No one forces you to say that the methods in the abstract class cannot be implemented in the abstract class, but if you actually implement it in the abstract class, provide it with an implementation code, c ++ does not complain, but the only way to call it is to "specify the name of its class when calling ". But you didn't find it. Even so, the implementation of pure virtual methods (functions) in abstract classes is redundant and its usage is limited.
This article is complete.
Troublemakers