请教高人,如何在C++中实现类似Java的接口?

来源:百度知道 编辑:UC知道 时间:2024/05/21 11:25:10
#include "stdafx.h"
#include <vector>

using namespace std;

class Ccomponent
{
public:
virtual void loop(void){
printf("do loop in Ccomponent\n");
}
};

class Cmsgbox : public Ccomponent
{
public:
void loop(void){
printf("do loop in Cmsgbox\n");
}
};

class Cbutton : public Ccomponent
{
public:
void loop(void){
printf("do loop in Cbutton\n");
}
};

int _tmain(int argc, _TCHAR* argv[])
{
vector<Ccomponent> components;
vector<Ccomponent>::iterator it;

Cbutton button;
components.push_back(button);
Cmsgbox msgbox;
components.push_back(msgbox);

for(it=components.begin();it!=components.end();it++){
//请问如何通过it来运行components中button和msgbox的loop()函数?

int main()
{
vector<Ccomponent*> components;//放指针类型
vector<Ccomponent*>::iterator it;
//vector<Cmsgbox>::iterator it;
Cbutton *button=new Cbutton;
components.push_back(button);
Cmsgbox *msgbox=new Cmsgbox;
components.push_back(msgbox);

for(it=components.begin();it!=components.end();it++){

(*it)->loop();
}
return 0;
}

Ccoment *base;
Cmsgbut dr1;
CButton dr2;
base=&dr1;
base->Loop();

base=&dr2;
base->Loop();