2017-05-17 35 views
1

一個靜態方法,我想有一類Sorings其中實現與模板的靜態方法的一些排序方法。我已閱讀here靜態模板方法應該在.h文件中實現。這裏是我的代碼:從調用模板類從其他文件C++

Sortings.h

#ifndef SORTINGS_H_ 
#define SORTINGS_H_ 

template <class T> 
class Sortings { 
public: 
    static void BubbleSort(T a[], int len, bool increasing) 
    { 
     T temp; 
     for(int i = len-1; i >= 1; i--) 
      for(int j = 0; j<= i-1; j++) 
       if(increasing ? (a[j] > a[j+1]) : (a[j] < a[j+1])) { 
        temp = a[j+1]; 
        a[j+1] = a[j]; 
        a[j] = temp; 
       } 
    }; 
}; 

#endif /* SORTINGS_H_ */ 

Sortings.cpp

#include "Sortings.h" 
//empty? 

Practice.cpp

#include <iostream> 
#include "Sortings.h" 
int main() { 
    int a[6] = {4,5,2,11,10,16}; 
    Sortings::BubbleSort<int>(a,6,true); 
    return 0; 
} 

但它返回以下錯誤:(線條像那樣,因爲我已經在Practice.cpp中評論了所有其餘部分)

Description Resource Path Location Type 
'template<class T> class Sortings' used without template parameters PracticeCpp.cpp /PracticeCpp/src line 41 C/C++ Problem 
expected primary-expression before 'int' PracticeCpp.cpp /PracticeCpp/src line 41 C/C++ Problem 
Function 'BubbleSort' could not be resolved PracticeCpp.cpp /PracticeCpp/src line 41 Semantic Error 
Symbol 'BubbleSort' could not be resolved PracticeCpp.cpp /PracticeCpp/src line 41 Semantic Error 

我不明白是什麼問題。你能幫助我理解什麼是錯的:在概念上還是/和語法上?

我與Eclipse Neon.3運行版本(4.6.3)

回答

1
template <class T> 
class Sortings { 

模板參數適用於類,而不是方法。所以你必須把它叫做Sortings<int>::BubbleSort(a,6,true);。換句話說,沒有類型命名爲Sortings。相反,該類型是Sortings<int>

而且你不需要Sortings.cpp,因爲一切是頭文件中。

雖然沒有直接問到問題,但我認爲你不需要在這裏上課。名稱空間內的簡單模板靜態方法可以正常工作。東西likie這樣的:

namespace Sorting { 

template<class T> 
static void BubbleSort(T a[], int len, bool increasing) { 
    // ... 
} 

} 

然後就可以調用Sorting::BubbleSort<int>(a,6,true)

+0

謝謝。我意識到我做了什麼。它的工作原理,當然,當我將模板聲明從類更改爲方法時,我的原始代碼工作。 – Veliko

1

你的模板類,而不是靜態方法!

因此,而不是使用Sortings::BubbleSort<int>你需要使用Sortings<int>::BubbleSort

在電話會議上
1

,您添加模板的功能,但是你宣佈對類的模板。

Sortings::BubbleSort<int>(a,6,true); 

應該成爲

Sortings<int>::BubbleSort(a,6,true);