C++-dynamic_cast的用处

主要用来在没有实现文件,只有头文件的情况下,添加派生类的功能,如下例给programmer加奖金。

注意:dynamic_cast不能用于没有virtual函数的类

///////////////////////////////////////////////////////////////////////////////
//
//  FileName    :   page_content.h
//  Version     :   0.10
//  Author      :   Ryan Han
//  Date        :   2013/07/26 16:50:14
//  Comment     :  
//
///////////////////////////////////////////////////////////////////////////////
#ifndef PAGE_CONTENT_H
#define    PAGE_CONTENT_H
class employee {
    public:
    virtual int salary();
};
    
class manager : public employee {
    public:
    int salary();
};

class programmer : public employee {
    public:
    int salary();
    void bonus();
};




#endif
///////////////////////////////////////////////////////////////////////////////
//
//  FileName    :   page_content.cpp
//  Version     :   0.10
//  Author      :   Ryan Han
//  Date        :   2013/07/26 16:50:14
//  Comment     :  
//
///////////////////////////////////////////////////////////////////////////////
#include "page_content.h"

#include <iostream>
using namespace std;

int employee::salary() {
    cout << "employee::salary() was called. " << endl;
}

int manager::salary() {
    cout << "manager::salary() was called. " << endl;
}

int programmer::salary() {
    cout << "programmer::salary() was called. " << endl;
}
///////////////////////////////////////////////////////////////////////////////
//
//  FileName    :   page_content_client.cpp
//  Version     :   0.10
//  Author      :   Ryan Han
//  Date        :   2013/07/26 16:50:14
//  Comment     :  
//    Output        :
//    $ ./a
//    payroll was called.
//    employee::salary() was called.
//    This is not programmer
//    payroll was called.
//    programmer::salary() was called.
//    New added programmer::bonus() was called.
///////////////////////////////////////////////////////////////////////////////
#include "page_content.h"

#include <iostream>
using namespace std;

void payroll(employee *pe) {
    cout << "payroll was called. " << endl;
    pe->salary();
    
    programmer* pm = dynamic_cast<programmer*>(pe);
    
    if(pm)
        pm->bonus();
    else
        cout << "This is not programmer" << endl;
}

void programmer::bonus() {
    cout << "New added programmer::bonus() was called. " << endl;
}

int main() {

    employee* pe = new employee();
    
    payroll(pe);
    
    programmer* pp = new programmer();
    
    payroll(pp);
    
    return 0;
}
原文地址:https://www.cnblogs.com/dracohan/p/3813384.html