C ++ collection (2)

Source: Internet
Author: User
    1. Virtual Functions

The function declared in the base class can be redefined in each derived class. For example

 
1: # Include<Iostream>

 
2: # Include<String>

 
3: Using NamespaceSTD;

 
4: ClassEmployee {

 
5:String first_name, family_name;

6:ShortDepartment;

 
7: Public:

 
8:Employee (ConstString & N,IntD );

 
9:Virtual VoidPrint ()Const;

 
10:};

11: VoidEmployee: Print ()Const{

 
12:Cout <family_name <Department <Endl;

 
13:}

 
14:Employee: employee (ConstString & N,IntD): first_name (N), Department (d ){}

 
15: ClassManager:PublicEmployee {

16:// List <employee *> group;

 
17:ShortLevel;

 
18: Public:

 
19:Manager (ConstString & N,IntD,IntLVL );

 
20:VoidPrint ()Const;

21:};

 
22:MANAGER: Manager (ConstString & N,IntD,IntLVL): employee (n, d), level (LVL ){}

 
23: VoidMANAGER: Print ()Const

 
24:{

 
25:Employee: Print ();

 
26:Cout <level <Endl;

27:}

 
28: IntMain ()

 
29:{

 
30:Employee E ("Brown", 1234 );

 
31:Manager M ("Smith", 1234,2 );

 
32:E. Print ();

 
33:M. Print ();

34:Employee * P = & E;

 
35:P-> Print ();

 
36:P = & M;

 
37:M. Print ();

 
38:Manager * q = & M;

 
39:Q-> Print ();

 
40:

41:}

 

The base class declares a virtual function virtual void print () const; used to print the information of class members. Define the specific content of the print function in the base class and the derived class respectively.

Define a pointer to the base class object in the implementation, and assign values to the base class and the object address of the derived class respectively. Then call the print function through the pointer. We can find that the print function defined by the base class and the derived class is called respectively.

Which of the following Derived classes does the indicated object belong? Through virtual functions, we solve this problem.ProgramThe output is:

 
1:1234

 
2:1234

 
3:2

 
4:1234

 
5:1234

 
6:2

 
7:1234

 
8:2

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.