2012-12-22 24 views
2

好吧,我來自Java和Python,請耐心等待。我一直在網上搜索,試圖學習如何在C++中使用頭文件,而且我還沒有做好,直到我定義了一個類。這是我的代碼。如何實現.h文件中定義的類C++

的notAClock.h

#ifndef NOTACLOCK_H_ 
#define NOTACLOCK_H_ 

namespace thenewboston { 

class notAClock { 
public: 
    notAClock(); 
    virtual ~notAClock(); 
    int isAClock(); 
}; 

} /* namespace thenewboston */ 
#endif /* NOTACLOCK_H_ */ 

的notAClock.cpp

/* 
* notAClock.cpp 
* 
* Created on: Dec 22, 2012 
*  Author: pipsqueaker 
*/ 

#include "notAClock.h" 

namespace thenewboston { 

notAClock::notAClock() { 
    // TODO Auto-generated constructor stub 

} 

notAClock::~notAClock() { 
    // TODO Auto-generated destructor stub 
} 

int notAClock::isAClock() { 
    return 0; 
} 
} /* namespace thenewboston */ 

,最後,我的主文件

#include <iostream> 
#include "notAClock.h" 
using namespace std; 

int main() { 
    cout << "program works" << endl; 
    notAClock play; 
} 

當Eclipse嘗試編譯這對我來說(我使用CDT插件)會引發錯誤,其中的相關部分是

../src/main.cpp:13: error: 'notAClock' was not declared in this scope 
../src/main.cpp:13: error: expected `;' before 'play' 
make: *** [src/main.o] Error 1 

我能從中得到的最多就是notAClock在主類中是未定義的。我究竟做錯了什麼?

-pipsqueaker117

+4

你把它放在一個名字空間中,所以它是'newboston :: notAClock'。 –

+1

你已經做了很多工作來把這個類放在一個單獨的命名空間中。不要驚訝它現在隱藏在那裏:-) – Mat

回答

4

你有一個名字空間裏面的類。它需要有資格使用它:

thenewboston::notAClock play; 

或者添加using指令,允許類不合格訪問:

using thenewboston::notAClock; 
notAClock play; 

還是一個using namespace指令在整個命名空間拉:

using namespace std; 
using namespace thenewboston; 

int main() { 
    cout << "program works" << endl; 
    notAClock play; 
} 
+0

謝謝,刪除名稱空間引用完美工作。我將不得不瞭解後面的命名空間,不過,謝謝! – pipsqueaker117

+0

@ pipsqueaker117命名空間用於引入聲明符號的顯式作用域。它們旨在防止兩個或更多共享相同名稱的符號之間發生名稱衝突。例如,C運行庫(CRT)以及C++標準庫都聲明'double sqrt(double)'。爲了防止名稱衝突,後者被放置在'std'命名空間中,即'double std :: sqrt(double)'。 – IInspectable

0

要解決「如何在C++中使用頭文件」這個問題的一部分,請注意幾點:

1)C++中的頭文件與java或python中的包導入不同:當你在C++中包含文件時,文件的文本在編譯過程中被包含到源文件中(忽略預編譯頭文件,這是一種優化) ,以及與正在編譯的文件一起編譯的內容。所以這意味着在整個項目中經常包含的任何頭文件都會被重複編譯。這就是爲什麼要在C++中保持絕對最小值的理由。 2)就風格而言,許多人更喜歡只在公共頭文件中保留公共頭文件聲明(例如,參見「pimpl」成語),並將具體類定義放入.cpp文件中。這使得類的實現的內部細節與其公共接口保持物理分離。當類的實現發生變化時,只有具有實現代碼的文件需要重新編譯。如果將類的實現放在廣泛的頭文件中,那麼不僅在開發過程中會產生更多和更長的構建,而且非相關代碼更可能「混淆」類的實現並導致難以實現 - 調試問題。

相關問題