发布网友 发布时间:2023-06-15 11:02
共1个回答
热心网友 时间:2024-11-24 09:39
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;
}