C++中如何实现像Java中接口功能
2018-05-29 · 百度知道合伙人官方认证企业
C++可以用纯虚函数实现类似于JAVA中接口的功能:
class Client {
public:
void process() {
msg_ = read();//假设read返回string类型数据
if(interface_) {
interface_->pose_status(msg_); //实际执行了MainWindow中实现的接口方法
}
}
class ClientInterface { //定义接口类
public:
virtual void pose_status(string msg) = 0; //接口方法
......
}
void register(ClientInterface *interface) { //实现接口类的纯虚函数(接口方法)的类调用此函数进行注册
interface_ = interface;
}
private:
string msg_;
ClientInterface *interface_;
}
class MainWindow:public Client::ClientInterface {
pubulic:
MainWindow() {
client.register(this);
}
void pose_status(string msg) {
process(msg);//获得并处理msg数据
}
private:
Client client;
}