全纯虚函数(类似Java接口)的应用 -- 回调功能
// TODO 全纯虚函数(类似Java接口)的应用 -- 回调功能
#include <iostream>
using namespace std;
// 登录响应的接口 成功,错误
class ILoginResponse {
public:
// 登录成功
virtual void loginSuccess(int code, string message, string data) = 0;
// 登录失败
virtual void loginError(int code, string message) = 0;
};
// 写一个实现类,继承接口
class ILoginResponseImpl : public ILoginResponse {
public:
// 登录成功
void loginSuccess(int code, string message, string data) override {
cout << "loginSuccess " << "code:" << code << " message:" << message
<< "data:" << data << endl;
}
// 登录失败
void loginError(int code, string message) override {
cout << " loginError " << "code:" << code << " message:" << message << endl;
}
};
// 登录的API动作
void loginAction(string name, string pwd, ILoginResponse &loginResponse) {
if (name.empty() || pwd.empty()) {
cout << "用户名或密码为空!" << endl;
return;
}
if ("Jin" == name && "123" == pwd) {
loginResponse.loginSuccess(200, "登录成功", "{name=jin}");
} else {
loginResponse.loginError(404, "登录错误,用户名或密码错误...");
}
}
int main() {
// Allocating an object of abstract class type 'ILoginResponse'
// 正在分配抽象类型为ILoginResponse的对象 不能被实例化
/*new ILoginResponse() {
// 登录成功
void loginSuccess(int code, string message, string data) {
}
// 登录失败
void loginError(int code, string message) {
}
}*/
// 纠结:为什么不可以
// 1.他不是Java的接口,C++也没有接口,他只是像接口而已。
// 2.他也不是抽象类,C++也没有抽象类,他只是像抽象类而已。
// 3.他是纯虚函数的类,此类决定不准你实例化
string username;
cout << "请输入用户名.." << endl;
cin >> username;
string userpwd;
cout << "请输入密码.." << endl;
cin >> userpwd;
ILoginResponseImpl iLoginResponse;
loginAction(username, userpwd, iLoginResponse);
return 0;
}
失败
成功