1 Experiment with Virtual Keywords 1.1 change virtual function access in a derived class
Defines two classes, a A, where B public derives from a. A defines a private member virtual function func,b This function, but sets its access rights to public
classa{Private: Virtual voidfunc () {printf ("a\n"); }}; classB: Publica{ Public: voidfunc () {printf ("b\n"); } voidDo_func () {func (); }};intMain () {/*test-1 * Compile error, error: ' virtual void a::func () ' is private * analysis: The access rights of the virtual modifier function in the base class should not be changed in the derived class, otherwise the polymorphism is limited, compared t Est-1 and Test-2**/A* B =NewB; b-func (); /*test-2 * Compile, run successfully, * output: B **/B* B =NewB; b-func (); /*test-3 * Compile, run successfully, * output: B **/A* B =NewB; b-Do_func (); return 0;}
2 Enumeration Classes
There is now a requirement to construct objects that are based on a given template and do not allow arbitrary construction. For example, to create a new family name class, but the last name is fixed, not allowed to arbitrarily construct a new surname, so you can define the enumeration class. The constructor (copy, assignment) other than family_name (const char * Name) is set to public. Several static family_name are then defined for use by the user.
Note: Enum classes cannot be abstract classes
classfamily_name{Private: Family_name (Const Char*name): name_ (name) {}Const Char*name_; Public: Family_name (ConstFamily_name &Other ) {name_=other.name_; } family_name&operator=(ConstFamily_name &Other ) {name_=other.name_; return* This; } Public: StaticFamily_name Yang; StaticFamily_name Zhang; StaticFamily_name Liu; StaticFamily_name Zhao;}; Family_name Family_name::yang ("Yang"); Family_name Family_name::zhang ("Zhang"); Family_name Family_name::liu ("Liu"); Family_name Family_name::zhao ("Zhao");intMain () {Family_name a=Family_name::yang; return 0;}
C + + Tricks