无法创建对象并使用其模板类方法
Unable to create an object and use its methods of template class
我对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);
相关文章:
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何获取在 main() 函数中构造的类的创建对象?
- 在类中创建对象
- 从类模板创建对象的工厂函数模板?
- C++ 在其自己的类中创建对象的修改副本
- 使用抽象类的类和实现此抽象类的创建对象
- 如何创建具有某些规则的类来创建对象
- 使用C 中的字符串从类名称创建对象
- 为类方法创建模板
- 对基类方法slice对象的c++调用
- 如何使用构造函数在另一个类中创建对象
- C++在类外创建对象
- 我在尝试在类中创建对象时面临如何解决链接错误
- c++如何用类Template创建对象
- 在类中创建对象之前调用函数
- 从类中创建对象ArrayList
- 在类中创建对象的最佳实践
- c++成员初始化列表/在类中创建对象
- 需要帮助在类中创建对象,并为成员函数赋值
- 如何在另一个类中创建对象