C + + Tricks

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.