无法创建对象并使用其模板类方法

Unable to create an object and use its methods of template class

本文关键字:类方法 创建对象      更新时间:2023-10-16

我对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 {       
  ~~~~~~~~~~~~~~~~~~~~~~~~       ^        

有什么建议吗?

第一个错误,nCr是模板类,提到它时需要指定模板参数,比如nCr<int>

第二个错误,nCr<int> x(4,2);意味着通过其构造函数构造一个nCr<int>,该构造函数接受两个参数,但nCr没有这样的构造函数。相反,你在nCr中定义operator(),所以你可能的意思是

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

由于它是一个模板类,请指定参数:

nCr<int> x;

由于没有匹配的构造函数,因此nCr<int> x(4,2) // doesn't work

首先声明 x ,然后调用您在类中定义的operator()

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