C++中,虚函数与容器(vector)的巧妙组合
#include <iostream>
#include <vector>
using namespace std;
class base //纯虚基类
{
public:
virtual void init() = 0;
virtual void start() = 0;
virtual void end() = 0;
};
class other1
{
public:
void logprint1()
{
cout<<"print err1"<<endl;
};
};
class other2
{
public:
void logprint2()
{
cout<<"print err2"<<endl;
};
};
class rea1:public other1,public base
{
public:
void init()
{
cout<<"rea1"<<endl;
};
void start()
{
cout<<"start1"<<endl;
};
void end()
{
cout<<"end1"<<endl;
logprint1();
};
};
class rea2:public other2,public base
{
public:
void init()
{
cout<<"rea2"<<endl;
};
void start()
{
cout<<"start2"<<endl;
};
void end()
{
cout<<"end2"<<endl;
logprint2();
};
};
int main()
{
vector<base *> myvec;
vector<base *>::iterator itr;
rea1 crea1;
rea2 crea2;
myvec.push_back(&crea1);
myvec.push_back(&crea2);
for (itr = myvec.begin(); itr != myvec.end(); itr++) //打印出来
{
(*itr)->init();
(*itr)->start();
(*itr)->end();
}
return 0;
}
补充:软件开发 , C++ ,