2016-04-28 74 views
0

我對於在C++中使用模板非常新穎。 以下是我正在嘗試使用的代碼。我無法使用以下代碼,因爲我無法弄清楚如何爲其創建對象並使用其中定義的方法。無法創建對象並使用其模板類的方法

template <typename UInt> class nCr { 
    public: 
     typedef UInt result_type; 
     typedef UInt first_argument_type; 
     typedef UInt second_argument_type; 

     result_type operator()(first_argument_type n, second_argument_type k) { 
      if (n_ != n) { 
       n_ = n; 
       B_.resize(n); 
      } // if n 

      return B_[k]; 
     } // operator() 

    private: 
     int n_ = -1; 
     std::vector<result_type> B_; 

    }; 

以及如何我創建的對象是:

#include <iostream> 
#include "math.hpp" // WHere the above class nCr is defined 

int main() { 
    int n =4; 
    nCr x(4,2); 

    return 0; 
} 

爲了這個,我創建了錯誤的

error: use of class template 'jaz::Binom' requires template arguments  
     nCr x(4,2);   
      ^
./include/math.hpp:68:34: note: template is declared here  
    template <typename UInt> class nCr {  
    ~~~~~~~~~~~~~~~~~~~~~~~~  ^  

有什麼建議?

回答

5

第一個錯誤,nCr是一個模板類,當您提到它時需要指定模板參數,例如nCr<int>

的第二錯誤,nCr<int> x(4,2);裝置構造經由它的構造,其採用兩個參數一nCr<int>,但nCr不具有這樣的構造函數。相反,你在nCr定義operator(),所以你可能意味着

nCr<int> x; 
int result = x(4, 2); 
0

由於它是一個模板類,指定參數:

nCr<int> x; 

由於沒有匹配的構造函數,nCr<int> x(4,2) // doesn't work

首先聲明x,並致電operator(),您在類中定義:

nCr<int> x; 
int value = x(4,2);