2016-08-18 50 views
-1

错误:的`GameKey :: getGameKeywords()”C++多个定义[错误]

GameKey.cpp和.h原因错误多个定义,而ExitKey.cpp和.h基本上完全相同的类和头但不会产生错误。

(我知道如何使用空间std整件事)

//Function Declarations 
#ifndef GAMEKEY_H 
#define GAMEKEY_H 

// C++ libraries 
#include <iostream> 
#include <fstream> 
#include <string> 
#include <vector> 
#include <iterator> 
#include <algorithm> 

using namespace std; 

class GameKey 
    { 
     private: 
      string keyString; 
      string lineData; 

     public: 
      // Default constructor 
      GameKey(); 
      // Deconstructor 
      ~GameKey(); 
      // Get keywords 
      string getGameKeywords(); 
    }; 
#endif 

GameKey.cpp

//Function Definitions 
#include "GameKey.h" 

// Constructor 
GameKey::GameKey() 
    { 
    } 
// Deconstructor 
GameKey::~GameKey() 
    { 
    } 
// Get keywords 
string GameKey::getGameKeywords() 
    { 
     ifstream infile; 
     infile.open("GameKey.txt"); 
     while (getline(infile, lineData)) 
      {  
       keyString.append(lineData); 
       keyString.append("\n"); 
      } 
     infile.close(); 
     return keyString; 
    } 

ExitKey.h

//Function Declarations 
#ifndef EXITKEY_H 
#define EXITKEY_H 

// C++ libraries 
#include <iostream> 
#include <fstream> 
#include <string> 
#include <vector> 
#include <iterator> 
#include <algorithm> 

using namespace std; 

class ExitKey 
    { 
     private: 
      string keyString; 
      string lineData; 

     public: 
      // Default constructor 
      ExitKey(); 
      // Deconstructor 
      ~ExitKey(); 
      // Get keywords 
      string getExitKeywords(); 
    }; 
#endif 

ExitKey.cpp

//Function Definitions 
#include "ExitKey.h" 

// Constructor 
ExitKey::ExitKey() 
    { 
    } 
// Deconstructor 
ExitKey::~ExitKey() 
    { 
    } 
// Get keywords 
string ExitKey::getExitKeywords() 
    { 
     ifstream infile; 
     infile.open("ExitKey.txt"); 
     while (getline(infile, lineData)) 
      {  
       keyString.append(lineData); 
       keyString.append("\n"); 
      } 
     infile.close(); 
     return keyString; 
    } 

感谢您的帮助!

+0

有没有可能是有另一个文件(不是'GameKey.cpp'),它定义'GameKey :: getGameKeywords()'? – Rakete1111

+1

请发布[最小,完整和可验证示例](http://stackoverflow.com/help/mcve)。无法在我的本地环境中重现(Windows 7,gcc 4.8.1,编译命令='g ++ ExitKey.cpp GameKey.cpp main.cpp -o main')'main.cpp'的内容是'int main() {}'。 – MikeCAT

+0

@ Rakete1111不幸的是,我不这么认为。 – Sean

回答

1

我想你也许包括GameKey.cpp,而不是其他地方GameKey.h

+0

main.cpp包含GameKey.h,而不是.cpp – Sean

0

我不能肯定是用于编译的命令没有公布。

一种可能性是在编译命令中重复文件名也可能导致此错误。

例如: -

g++ ExitKey.cpp GameKey.cpp GameKey.cpp main.cpp -o main 
+0

我是编程新手,我对用于编译的命令一无所知。我使用的是使用MinGW编译器的Dev C++。我如何访问编译命令? – Sean

+0

我猜你正在Windows环境中使用Dev C++。在这种情况下,我认为你可能在你的主文件中包含了“GameKey.cpp”而不是“GameKey.h”。 –

+0

当你点击编译并在Dev C++窗口中运行时,你执行一个像我在MinGW编译器的回答中提到的命令。该命令用于编译unix shell中的C++代码。 希望它有帮助。祝你好运! –