我正在尝试创建一个 User
类,但是每当我尝试编译此代码时都会收到错误输出:
#ifndef LOGIN_H
#define LOGIN_H
#include <string>
/* Classes */
class User {
std::string username, password;
public:
void set_user_username (std::string);
void set_user_password (std::string);
};
// Sets the User's username
void User::set_user_username (std::string input) {
username = input;
}
// Sets the User's password
void User::set_user_password (std::string input) {
password = input;
}
#endif // LOGIN_H
multiple definition of `User::set_user_username(std::string)'
知道为什么它会给我这个错误消息吗?
最佳答案
您在头文件内部定义了 set_user_username()
和 set_user_password()
方法的主体,但在类声明之外。因此,如果您将此头文件包含在多个翻译单元中,无论是否使用头文件保护,链接器都会看到多个定义相同方法的目标文件并由于违反 One Definition Rule 而失败。 .
您需要:
将定义移动到它们自己的翻译单元,然后在您的项目中链接该单元:
登录.h
#ifndef LOGIN_H #define LOGIN_H #include <string> /* Classes */ class User { std::string username, password; public: void set_user_username (std::string); void set_user_password (std::string); }; #endif // LOGIN_H
登录.cpp
#include "Login.h" // Sets the User's username void User::set_user_username (std::string input) { username = input; } // Sets the User's password void User::set_user_password (std::string input) { password = input; }
在类声明中内联移动定义:
登录.h
#ifndef LOGIN_H #define LOGIN_H #include <string> /* Classes */ class User { std::string username, password; public: void set_user_username (std::string input) { username = input; } void set_user_password (std::string input) { password = input; } }; #endif // LOGIN_H
关于c++ - “多重定义”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49162723/