c++ 编写api接口
时间: 2023-09-05 19:06:56 浏览: 190
编写 API 接口的方式和语言并没有直接关系,但是常见的方式是使用 C++ 编写后端服务,并在其中实现 API 接口。以下是一个简单的 C++ API 接口的示例:
```cpp
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <memory>
#include <map>
class Api {
public:
virtual std::string execute(const std::vector<std::string>& args) = 0;
};
class EchoApi : public Api {
public:
std::string execute(const std::vector<std::string>& args) override {
std::stringstream ss;
for (const auto& arg : args) {
ss << arg << " ";
}
return ss.str();
}
};
class ApiManager {
public:
void registerApi(const std::string& name, std::shared_ptr<Api> api) {
api_map_[name] = api;
}
std::string execute(const std::string& name, const std::vector<std::string>& args) {
if (api_map_.count(name) == 0) {
return "Api not found: " + name;
}
auto api = api_map_[name];
return api->execute(args);
}
private:
std::map<std::string, std::shared_ptr<Api>> api_map_;
};
int main() {
ApiManager api_manager;
auto echo_api = std::make_shared<EchoApi>();
api_manager.registerApi("echo", echo_api);
std::vector<std::string> args{"Hello,", "world!"};
std::cout << api_manager.execute("echo", args) << std::endl;
return 0;
}
```
这个示例中,我们定义了一个 `Api` 接口和一个具体的实现 `EchoApi`,并将它们放入一个 `ApiManager` 中进行管理。在 `main()` 函数中,我们先将 `EchoApi` 注册到 `ApiManager` 中,并调用 `execute()` 函数传入参数执行接口。通过这个示例,我们可以看到 C++ 的面向对象编程风格和内存管理方式,以及如何使用容器和智能指针等 C++ 特性来实现 API 接口。
阅读全文
相关推荐















