2013-02-09 213 views
3

我有一個叫做Player的類,它有一個構造函數,它接受5個在我的「player.h」文件中聲明的float參數,然後在我的「player.cpp」文件中進行初始化如帖子底部所示。從C++的另一個來源訪問類,初始化構造函數

每當我試着運行該程序,我得到的錯誤:

build/Debug/MinGW-Windows/player.o: In function `Player': 
C:\Users\User\Dropbox\NetBeans Workspace\Testing/player.cpp:11: multiple definition of `Player::Player(float, float, float, float, float)' 
build/Debug/MinGW-Windows/main.o:C:\Users\User\Dropbox\NetBeans Workspace\Testing/player.h:20: first defined here 

我在做什麼錯在這裏?我試圖在構造函數之前擺脫「public:」,但那根本沒有幫助。它說我有構造函數的多個定義,但我只初始化它一次。我相信這是明顯的。

兩個文件的完整來源:

「player.cpp」

#include "player.h" 

Player::Player(float x, float y, float z, float rx, float ry) { 

} 

「player.h」

#ifndef PLAYER_H 
#define PLAYER_H 

class Player { 

public: 

    Player(float x, float y, float z, float rx, float ry); 
}; 

#endif 
+0

在行''player.h'的20'什麼?因爲它看起來像你在那裏首先實現它。 – 2013-02-09 23:44:20

+0

空行?奇怪的 – CoderTheTyler 2013-02-09 23:46:50

+0

你的'main.cpp'看起來像什麼?我懷疑你可能有#include「player.cpp」而不是'#include「player.h」'。 – 2013-02-09 23:55:35

回答

5

您可能還沒有保護你的.h文件。

您可以在main.cpp中包含player.h,它爲此編譯單元獲取一個定義。 然後它被包含在player.cpp中,在那裏得到第二個定義。

如果你的編譯器不支持#pragma once,你必須手動保護他們經典

#ifndef PLAYER_H 
#define PLAYER_H 

// all your class definition code here 

#endif 
+3

'#pragma once',儘可能好,不符合標準。請使用符合C++的答案。 – 2013-02-09 23:45:53

+0

@KonradRudolph它確實應該是。畢竟,我們進入了二十一世紀。 – 2013-02-09 23:47:20

+0

@Bartek這不是重點。我想用C++標準來做很多事情。 – 2013-02-09 23:49:41