c++ - “多重定义”错误

标签 c++

我正在尝试创建一个 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/

相关文章:

c++ - 错误 : 'A' is an inaccessible base of 'B'

c++ - 在 C++ 中干净地复制基类或子类的实例?

C++ 错误 : unable to find string literal operator

android - openfl - 音频不适用于 cpp 目标

c++ - 编写一个 ostream 过滤器?

python - 如何将 C++ 函数周围的 R 包装器转换为 Python/Numpy

c++ - omp 缩减和 lambda 函数

c++ - 如何在 Objective C 中实现 C++ 观察者模式

c++ - 测试 C++ 轮询套接字功能

c++ - 在调用析构函数之前对象的生命周期结束了吗?