我正在學習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 ...問題解決了!謝謝!
請顯示主程序。 – Brian
在Boat.cpp中添加一個簡單的主要部分 - 它在最近的gcc上爲我編譯。請顯示完整的示例包含編譯器調用。 –
您是否有機會從'Main.cpp'包含'Boat.cpp'而不是'Boat.h'? –