When using a pure virtual function
Some classes, in reality point of view and perspective of the project do not need to instantiate (it does not need to create objects), some members of this class are defined only to provide a formal interface, ready to do a specific subclass achieve. At this time, this method can be defined as "pure virtual functions", it contains pure virtual function, called an abstract class.
Use pure virtual function
Using virtual pure specifier , "= 0" a method is defined as a pure virtual function, class belongs will become abstract class:
. 1 #include <the iostream> 2 #include < String > . 3 . 4 the using namespace STD; . 5 . 6 class the Shape . 7 { . 8 public : . 9 the Shape ( const String & Color = " White " ) 10 { . 11 the this -> Color = Color; 12 is } 13 is 14 virtual a float area () = 0 ; // Virual = 0 and a class area () is defined as a pure virtual function, can not create object belongs 15 16 Private : . 17 String Color; 18 is }; . 19 20 is int main () 21 is { 22 is the Shape A ; // the Shape objects can not be created, being given 23 }
An abstract class can not create an object, such as code on line 22 will be given:
Correct usage of pure virtual functions
. 1 #include <the iostream> 2 #include < String > . 3 . 4 the using namespace STD; . 5 . 6 class the Shape . 7 { . 8 public : . 9 the Shape ( const String & Color = " White " ) 10 { . 11 the this -> Color = Color; 12 is } 13 is 14 virtual a float area () = 0 ; // Virual = 0 and a class area () is defined as a pure virtual function, can not create object belongs 15 16 Private : . 17 String Color; 18 is }; . 19 20 is class Circle: public the Shape 21 is { 22 is public : 23 is Circle ( a float RADIUS = 0 , const String & Color = " White " ): the Shape (Color), R & lt (RADIUS) {} 24 25 @ subclasses need to override pure virtual functions of the parent class, or inherited pure virtual functions, also becomes an abstract class Circle 26 is a float Area () { return 3.1 * R & lt * R & lt;} 27 28 private: 29 float r; //半径 30 }; 31 32 int main() 33 { 34 Circle c_1(10); 35 cout << c_1.area() << endl; 36 }
After the code line 26, the subclass inherits the abstract class, subclass that does not override pure virtual functions of the parent class, then the subclass of abstract class will also be changed. Subclasses need to override this function, do the implementation.
=========================================================================================================================