2016-09-02 16 views
2

私はこのエラーをたくさん見ましたが、ここにはたくさんの質問がありますが、今は本当に何をすべきかわかりません。エラー:クラス[クラス名]の再定義

User.h

#ifndef USER_H 
#define USER_H 
#endif // USER_H 

#include <iostream> 
using namespace std; 


class User 
{ 
private: 
    struct Accounts {string user, password, name;} accounts[2]; 
    void setAccounts(); 

public: 
    int Access(string user, string password); 
    bool online; 

    User(); 
    ~User(); 
}; 

User.cpp

#include "User.h" 

#include <iostream> 

User::User() {/* data */} 
User::~User() {/* data */} 

void User::setAccounts() 
{ 
    accounts[0].user = "user01"; 
    accounts[0].password = "pw01"; 
    accounts[0].name = "hi"; 

    accounts[1].user = "user02"; 
    accounts[1].password = "pw02"; 
    accounts[1].name = "hi2"; 
} 

int User::Access(string user, string password) 
{ 
    unsigned short int i; 

    for (int i = 0; i <= 1; i++) 
    { 
     if (user.compare(this->accounts[i].user) == 0 and password.compare(this->accounts[i].password) == 0) 
      return 0; 
    } 

    return 1; 
} 

私も#pragma onceを使用しましたし、それはまだクラスを認識しません。 私は何をしますか?

@edit:私は#endif // USER_Hに移動しましたが、クラスが認識されましたが、コンストラクタメソッドがまだ見逃されました。

"error: multiple definitions of 'User::User()'"

+3

あなたのインクルードガードは...まあまあです。 – tkausl

+0

#pragmaが正しい場所に置かれていると仮定して#if .. #endif guard – SnoozeTime

+0

を取り除くと、#pragmaは一度正常になります。 – pm100

答えて

1

ヘッダーファイルの末尾に#endif // USER_Hを配置する必要があります。 #ifndef#endifの間のコンテンツのみが複数回含まれるように保護されています。

#ifndef USER_H 
#define USER_H 

#include <iostream> 
using namespace std; 

class User 
{ 
private: 
    struct Accounts {string user, password, name;} accounts[2]; 
    void setAccounts(); 

public: 
    int Access(string user, string password); 
    bool online; 

    User(); 
    ~User(); 
}; 

#endif // USER_H 

EDIT

あなたはUser.cppを含めるべきではありません。ヘッダーファイルのみを含める必要があります。

+0

まだ動作しません。コンパイラは、User :: User()の定義が複数あると言っています。それはまだコンパイラの問題です。 –

+0

@ChistéUser.cpp "どこかに#include"しましたか? – songyuanyao

+0

はい、私はmain.cppに入れました。それは間違っていますか? –

0

#endif // USER_Hをファイルの末尾に移動しますか?

+0

まだ動作しません。コンパイラは、User :: User()の定義が複数あると言っています。それはまだコンパイラの問題です。 –

関連する問題