Visitor模式
#include <iostream>
#include <string>
class emp;
class boss;
class visitor
{
public:
visitor(){};
~visitor(){};
virtual void visit( emp * emp ) {};
virtual void visit( boss * ss ) {};
};
class emp
{
int m_sdays, m_vdays;
float m_salarys;
std::string m_name;
public:
emp(std::string name, float salary, int sdays, int vdays):m_name(name),m_salarys(salary),m_sdays(sdays),m_vdays(vdays) { };
~emp(){};
std::string getname() {return m_name; };
float getsalary() {return m_salarys ; };
int getsdays() {return m_sdays; } ;
int getvdays() {return m_vdays; } ;
virtual void accept(visitor *v) { v->visit(this);};
};
class boss:public emp
{
public:
virtual void accept(visitor *v) { v->visit(this);};
};
class vacvisitor:public visitor
{
int m_totalvdays;
public:
vacvisitor():m_totalvdays(0){};
~vacvisitor(){};
int gettotalvdays(){ return m_totalvdays; } ;
virtual void visit( emp * emp ) { m_totalvdays += emp->getvdays(); };
virtual void visit( boss * boss ) { m_totalvdays += boss->getvdays(); };
};
int main()
{
emp array[2] = {emp("a",100, 1, 2 ),emp("b",100, 1, 2 )};
vacvisitor * vc = new vacvisitor();
for (int i = 0; i< sizeof(array)/sizeof(emp) ; i++)
{
array[0].accept(vc);
}
std::cout << vc->gettotalvdays()<<std::endl;
getchar();
return 0;
}
#include <string>
class emp;
class boss;
class visitor
{
public:
visitor(){};
~visitor(){};
virtual void visit( emp * emp ) {};
virtual void visit( boss * ss ) {};
};
class emp
{
int m_sdays, m_vdays;
float m_salarys;
std::string m_name;
public:
emp(std::string name, float salary, int sdays, int vdays):m_name(name),m_salarys(salary),m_sdays(sdays),m_vdays(vdays) { };
~emp(){};
std::string getname() {return m_name; };
float getsalary() {return m_salarys ; };
int getsdays() {return m_sdays; } ;
int getvdays() {return m_vdays; } ;
virtual void accept(visitor *v) { v->visit(this);};
};
class boss:public emp
{
public:
virtual void accept(visitor *v) { v->visit(this);};
};
class vacvisitor:public visitor
{
int m_totalvdays;
public:
vacvisitor():m_totalvdays(0){};
~vacvisitor(){};
int gettotalvdays(){ return m_totalvdays; } ;
virtual void visit( emp * emp ) { m_totalvdays += emp->getvdays(); };
virtual void visit( boss * boss ) { m_totalvdays += boss->getvdays(); };
};
int main()
{
emp array[2] = {emp("a",100, 1, 2 ),emp("b",100, 1, 2 )};
vacvisitor * vc = new vacvisitor();
for (int i = 0; i< sizeof(array)/sizeof(emp) ; i++)
{
array[0].accept(vc);
}
std::cout << vc->gettotalvdays()<<std::endl;
getchar();
return 0;
}