'Multiple Definition'错误



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

"用户::set_user_username(std::string("的多重定义

任何线索为什么给我这个错误消息?

您正在头文件内定义set_user_username()set_user_password()方法的主体,但在类声明之外。 因此,如果将此头文件包含在多个翻译单元中,则无论是否使用标头保护,链接器都将看到定义相同方法的多个对象文件,并且由于违反一个定义规则而失败。

您需要:

  • 将定义移动到其自己的翻译单元,然后在项目中链接该单元:

    登录.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
    

定义位于标题中,没有内联关键字。 使用 inline 关键字或将定义移动到 .cpp 文件中。

// Sets the User's username
inline void User::set_user_username (std::string input) {
    username = input;
}
// Sets the User's password
inline void User::set_user_password (std::string input) {
    password = input;
}

头文件中的多个定义

相关内容

最新更新