• c++拾遗(二)


    1. 虚函数

    使得在基类声明的函数能够在各个派生类里面重新定义。比如下面这个例子

       1: #include <iostream>
       2: #include <string>
       3: using namespace std;
       4: class Employee{
       5:     string first_name, family_name;
       6:     short department;
       7: public:
       8:     Employee(const string &n, int d);
       9:     virtual void print() const;
      10: };
      11: void Employee::print()const{
      12:     cout<<family_name<<department<<endl;
      13: }
      14: Employee::Employee(const string &n, int d):first_name(n),department(d){}
      15: class Manager:public Employee{
      16:     //list<Employee*> group;
      17:     short level;
      18: public:
      19:     Manager(const string &n, int d, int lvl);
      20:     void print()const;
      21: };
      22: Manager::Manager(const string &n, int d , int lvl):Employee(n,d),level(lvl){}
      23: void Manager::print() const
      24: {
      25:     Employee::print();
      26:     cout<<level<<endl;
      27: }
      28: int main()
      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: }

    基类声明了一个虚函数 virtual void print() const; 用来打印类成员的信息。在基类和派生类中分别定义print函数的具体内容。

    在实现中定义一个指向基类对象的指针,分别用基类和派生类的对象地址赋值。然后通过指针调用print函数,可以发现,调用的分别是基类和派生类定义的print函数。

    对于给定的类型为base*的指针,被指的对象到底属于哪个派生类呢?通过虚函数,我们解决了这个问题。程序的输出为:

       1: 1234
       2: 1234
       3: 2
       4: 1234
       5: 1234
       6: 2
       7: 1234
       8: 2
  • 相关阅读:
    Oracle 查询主外键关联
    maven
    LOG4J
    转换maven 项目为web 项目
    Iframe 高度自适应的问题
    JS 之CLASS类应用
    不要自己决定如何设计,遵从客户和客观需要
    私服搭建Nexus
    python经典算法题:无重复字符的最长子串
    Python输出hello world(各行命令详解)
  • 原文地址:https://www.cnblogs.com/bovine/p/2283609.html
Copyright © 2020-2023  润新知