[問題] class練習實作問題
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
code::blocks
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
no
問題(Question):
我是分成三個檔案來寫:main function, class definition, class implementation
compile時一直跳出錯誤訊息如下:
error: redefinition of 'Item::Item(bool, double)'|
error:'Item::Item(bool, double)' previously defined here|
程式碼(Code):(請善用置底文網頁, 記得排版)
main function:
#include <iostream>
#include "Item.h"
#include <iomanip>
using namespace std;
int main () {
Item Canon700D(3000.00);
//Canon700D.SetPrice(5700);
cout<<setw( 5 )<<Canon700D.ShowPrice()<<endl;
Item *Canon700DPtr = &Canon700D;
Canon700DPtr->SetPrice(5500);
cout<<setw( 5 )<<Canon700D.ShowPrice()<<endl;
Item Canon900D;
cout<<setw(5)<<Canon900D.ShowPrice()<<" Stock:"<<Canon900D.CheckStock;
}
Item.h:
#ifndef ITEM_H_INCLUDED
#define ITEM_H_INCLUDED
class Item
{
public:
Item (bool = false, double = 0) {
};
Item (double d2) {
SetPrice(d2);
};
void SetPrice(double x) {
price = x;
};
double ShowPrice() {
return price;
};
bool CheckStock(){
return instock;
};
private:
double price = 0;
bool instock;
};
#endif // ITEM_H_INCLUDED
item.cpp:
//因為某些因素,只有default constructor的implementation
#include <iostream>
#include <iomanip>
#include "Item.h"
using namespace std;
Item::Item (bool instock, double price) {
SetPrice(price);
CheckStock(instock);
}
我都照著課本上的格式寫(C++ How to Program 7/e)
之前沒有問題,加入default comstructor後就出現了前述的問題
因為基本上寫法和課本一樣,我也不知道怎麼不會過...
-------------------------------------------------------------------
後來我發現了,問題是在header裡面的default constructor裡面多寫了一個空括號
但程式碼正確後卻出現"undefined reference to WinMain@16"
看stack overflow上面,似乎改一下創建header的設定就可以
(http://tinyurl.com/ovgcf78)
不過我發現這時候把這定義丟回到header的下方就可以了
Item.cpp我把他刪掉。
這樣就compile成功了,結果也沒錯。
下次再試試他的那個方法好了。
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 218.164.162.203
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1442173235.A.274.html
※ 編輯: kiwistar (218.164.162.203), 09/14/2015 03:54:54
※ 編輯: kiwistar (218.164.162.203), 09/14/2015 03:55:13
※ 編輯: kiwistar (218.164.162.203), 09/14/2015 04:32:36
推
09/14 21:46, , 1F
09/14 21:46, 1F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章