2014-02-21 161 views
-2

個人項目我需要定義一個更好的優化模板類。模板類定義類型

我遵循示例,但它並沒有編譯,因爲我希望我的模板類從接口繼承。 有人能告訴我如何使用它,這裏是我的代碼:

我點HPP

template<typename T> 
class Container : public IOP 
{ 
public: 
    Container(); 
    T val; 
    int getpr() const; 
    IOP *operator+(const IOP &r) const; 
    IOP *operator-(const IOP &r) const; 
    IOP *operator*(const IOP &r) const; 
    IOP *operator/(const IOP &r) const; 
} 

我點CPP那裏是我的函數(構造函數...)

Container::Container() 
{ 

} 

int Container::getpr() 
{ 
... 
} 

... etc 

我想用我的班級像:

Container<long> test; 

Container<int> test; 

感謝您的任何幫助,鏈接或解釋。就目前

編譯錯誤:

Container.cpp:13:1: error: expected a class or namespace 
Container::Container() 
^ 
Container.cpp:13:12: error: C++ requires a type specifier for all declarations 
Container::Container() 
~~~~~~~~~^
Container.cpp:24:20: error: expected a class or namespace 
std::string const &Container::toString() 
       ^
Container.cpp:29:5: error: expected a class or namespace 
int  Container::getPrecision 

()

+3

您無法[在單獨的文件中定義模板](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file)。即使它是一個HPP文件,也可以使用 – user2079303

+0

?所以我必須在hpp文件或cpp中編寫整個類? – Gabson

+0

您只能在實例化模板的代碼所包含的文件中定義模板。如果你包含一個cpp文件,事情就會變得非常糟糕。從技術上講,如果你在聲明模板的頭文件中包含該文件,你可以在單獨的(頭文件)文件中定義模板(正如你可以在我鏈接的SO問題的第一個答案中看到的那樣)。 – user2079303

回答

1

,因爲這是模板類的實現,不要忘記提及<牛逼>:

template <class T> 
Container<T>::Container() 
{ 

} 

template <class T> 
int Container<T>::getpr() 
{ 
... 
} 

因爲在你的代碼這意味着您已經聲明模板類Container <T>並執行非模板類容器

+0

好的,我會試試這個。在每個類功能實施之前? – Gabson

+0

當然。這樣做,您可以指示編譯器「這是模板類X的實現,方法foo()」。如果你不想放置這麼長的表單,你必須在你的聲明中提供實現。 –