2014-02-20 25 views
0

我正在學習C++,目前正在嘗試創建一個非常基本的類來表示一艘船的長度和重量......看起來我遇到了試圖將它分解爲頭和cpp的問題文件。試圖在C++中實現一個基本的類

這些都是簡單的文件,我的工作......

Boat.h:

#ifndef BOAT_H_ 
#define BOAT_H_ 
class Boat{ 
public: 
    Boat(); 
    Boat(int,int); 

private: 
    int length; 
    int weight; 
}; 

#endif /* BOAT_H_ */ 

Boat.cpp:

#include "Boat.h" 

Boat::Boat(){ 
    length = 25; 
    weight = 2500; 
} 

Boat::Boat(int newLength, int newWeight){ 
    length = newLength; 
    weight = newWeight; 
} 

編譯時,我得到的錯誤Boat.cpp關於它是「首先在這裏定義的」。我一直在跟隨教程,並試圖像他們那樣做,但我似乎無法得到這個權利。這是完整的錯誤信息。我錯過了什麼?

C:\Documents and Settings\Administrateur\Bureau\Workspace\ClassTests\Debug/../Boat.cpp:4: multiple definition of `Boat::Boat()' 
Main.o:C:\Documents and Settings\Administrateur\Bureau\Workspace\ClassTests\Debug/..//Boat.cpp:4: first defined here 
Boat.o: In function `Boat': 
C:\Documents and Settings\Administrateur\Bureau\Workspace\ClassTests\Debug/../Boat.cpp:4: multiple definition of `Boat::Boat()' 
Main.o:C:\Documents and Settings\Administrateur\Bureau\Workspace\ClassTests\Debug/..//Boat.cpp:4: first defined here 
Boat.o: In function `Boat': 
C:\Documents and Settings\Administrateur\Bureau\Workspace\ClassTests\Debug/../Boat.cpp:9: multiple definition of `Boat::Boat(int, int)' 
Main.o:C:\Documents and Settings\Administrateur\Bureau\Workspace\ClassTests\Debug/..//Boat.cpp:9: first defined here 
Boat.o: In function `Boat': 
C:\Documents and Settings\Administrateur\Bureau\Workspace\ClassTests\Debug/../Boat.cpp:9: multiple definition of `Boat::Boat(int, int)' 
Main.o:C:\Documents and Settings\Administrateur\Bureau\Workspace\ClassTests\Debug/..//Boat.cpp:9: first defined here 

編輯: 我包括Boat.cpp主,而不是Boat.h ...問題解決了!謝謝!

+3

請顯示主程序。 – Brian

+0

在Boat.cpp中添加一個簡單的主要部分 - 它在最近的gcc上爲我編譯。請顯示完整的示例包含編譯器調用。 –

+8

您是否有機會從'Main.cpp'包含'Boat.cpp'而不是'Boat.h'? –

回答

0

看起來你已經將你的boat.cpp文件包含在有main函數的模塊中。你只需要在main模塊中包含header.h。

1

沒有辦法,以確保你做了什麼,但我還是設法與這個主要功能來生成錯誤:

#include "Boat.h" 
#include "Boat.cpp" 

int main(int argc, const char *argv[]) 
{ 
    Boat b; 

    return 0; 
} 

通過以下方式編譯:

g++ -O0 -ggdb main.cpp Boat.cpp -o main 

導致完全在你報告的錯誤中。無論你做了什麼 - 你似乎都試圖將Boat.cpp文件包括兩次,這樣你就可以將你的Boat類的定義加倍。