如何在C++另一头文件中引用std::map 拆分登录验证代码
拆分方案
1 拆分逻辑
按职责拆分两个独立头文件:
credential_store.h:负责静态凭证存储、封装查询能力,对应Data at Rest模块,完全不涉及用户输入、校验逻辑auth_validator.h:负责用户输入收集、有效性校验,对应Data in Motion和用户名检查模块
通过封装接口的方式规避之前std::map引用传递的编译错误,无需暴露内部存储结构。
2 头文件实现
2.1 credential_store.h(凭证存储模块)
#pragma once #include <map> #include <string> class CredentialStore { private: std::map<std::string, std::string> credential_map = { {"robert", "password123"}, {"wayne","password234"}, {"scott","password345"} }; public: // 对外仅暴露校验接口,不直接暴露内部map bool verify_credential(const std::string& username, const std::string& password) const { auto iter = credential_map.find(username); return iter != credential_map.end() && iter->second == password; } };
2.2 auth_validator.h(校验逻辑模块)
#pragma once #include "credential_store.h" #include <iostream> #include <string> bool do_login() { std::string username, password; // 收集用户输入 std::cout << "Enter Username" << std::endl; std::cin >> username; std::cout << "Enter Password" << std::endl; std::cin >> password; // 调用存储模块的接口做校验 CredentialStore store; return store.verify_credential(username, password); }
3 使用示例
在你的主程序中只需包含校验模块头文件即可调用:
#include "auth_validator.h" int main() { if (do_login()) { std::cout << "登录成功" << std::endl; } else { std::cout << "用户名或密码错误" << std::endl; } return 0; }
4 注意事项
- 所有头文件必须加
#pragma once(或#ifndef格式的头文件守卫),避免重复包含导致的编译错误 - 如果项目有多个源文件调用上述接口,建议把函数实现拆分到对应的
.cpp文件中,避免链接时出现重复定义错误 - 后续要加hash、加盐逻辑时,只需要修改
CredentialStore::verify_credential方法的实现即可,不需要改动校验模块的代码
内容的提问来源于stack exchange,提问作者pbgeek
相关产品推荐
相关产品推荐

