c++ 访问者模式

//写个基类
#ifndef Employee_hpp
#define Employee_hpp

#define CC_SYNTHESIZE(varType, varName, funName)\
protected: varType varName;\
public: virtual varType get##funName(void) const { return varName; }\
public: virtual void set##funName(varType var){ varName = var; }

#include <stdio.h>
#include <iostream>
#include "IVisiter.hpp"
using namespace std;
class Employee {
public:
    Employee() {};
    Employee(string name,int age): name(name),age(age) {};
    ~Employee() {};
    CC_SYNTHESIZE(string, name , Name);
    CC_SYNTHESIZE(int,age,Age);
    CC_SYNTHESIZE(IVisiter* , visiter, Visiter);
    virtual void showInfo();
    virtual void visit();
};
#endif /* Employee_hpp */


#include "Employee.hpp"

void Employee::showInfo() {
    printf("myname: %s , myage : %d\n", this->getName().c_str(),this->getAge());
}

void Employee::visit() {
    this->visiter->visit(this);
}

//继承基类Manager管理层类
#ifndef Manager_hpp
#define Manager_hpp

#include "Employee.hpp"
using namespace std;
class Manager: public Employee {
public:
    Manager() {};
    Manager(string name,int age): name(name),age(age) {};
    ~Manager() {};
    virtual void showInfo();
    CC_SYNTHESIZE(string, name , Name);
    CC_SYNTHESIZE(int,age,Age);
};
#endif /* Manager_hpp */

#include "Manager.hpp"

void Manager::showInfo() {
    printf("manager myname : %s , my age : %d \n" ,this->getName().c_str(),this->getAge());
}

//继承基类CommonEmployee普通员工层类
#ifndef CommonEmployee_hpp
#define CommonEmployee_hpp

#include "Employee.hpp"
using namespace std;
class CommonEmployee: public Employee {
public:
    CommonEmployee() {};
    CommonEmployee(string name,int age): name(name),age(age) {};
    ~CommonEmployee() {};
    virtual void showInfo();
    CC_SYNTHESIZE(string, name , Name);
    CC_SYNTHESIZE(int,age,Age);
};
#endif /* CommonEmployee_hpp */
#include "CommonEmployee.hpp"

void CommonEmployee::showInfo() {
    printf("CommonEmployee myname: %s ,myage : %d\n",this->getName().c_str(),this->getAge());
}

//继承基类IVisiter访问者接口
#ifndef IVisiter_hpp
#define IVisiter_hpp

#include <stdio.h>
class Employee; //由于Employee于IVisiter头文件定义相互包含 所以以class定义 在cpp文件再引入
class IVisiter {
public:
    IVisiter() {};
    ~IVisiter() {};
    virtual void visit(Employee* emp);
};
#endif /* IVisiter_hpp */
#include "IVisiter.hpp"
#include "Manager.hpp"
#include "Employee.hpp"
void IVisiter::visit(Employee* emp) {
    printf("我访问\n");
    emp->showInfo();
}

/*
  访问者模式
 */

#include <iostream>
#include "IVisiter.hpp"
#include "Manager.hpp"
#include "CommonEmployee.hpp"
int main(int argc, constchar * argv[]) {
    // insert code here...
    std::cout << "Hello, Visiter!\n";
    IVisiter *visiter = new IVisiter();
    Manager* manger = new Manager("lihua",40);
    CommonEmployee* emp = new CommonEmployee("xiaohua",20);
    manger->setVisiter(visiter);
    emp->setVisiter(visiter);
    
    manger->visit();
    emp->visit();
    return 0;
}


你可能感兴趣的:(C++,类,C语言,库)