简体   繁体   English

在C ++中将函数用作类成员

[英]Using function as class member in C++

I have came from Java, I have some knowledge of C++ and C, but not deep. 我来自Java,虽然我对C ++和C有所了解,但并不深入。 I am creating hashtable class, it will encapsulate storing values and keys. 我正在创建哈希表类,它将封装存储值和键。 But the question is what is a better approach to pass, for example, in constructor custom function which will calculate a hash key in the table. 但是问题是,例如在构造函数自定义函数中传递哪种更好的方法,该函数将在表中计算哈希键。

In java I would use function (interface) setting it as class member. 在Java中,我将使用函数(接口)将其设置为类成员。 What is the best practice to do this in C++, use the function pointer as member? 在C ++中使用函数指针作为成员的最佳实践是什么? Please suggest how to implement this. 请建议如何实施。

The C++ practice is to parametrize your class with callable type that will calculate the hash: C ++的做法是使用可计算类型的可调用类型对您的类进行参数化:

template<class Key, class Value, class Hash> class hashtable;

This allows to have any callable object as your hash function, be it plain function or functor object. 这允许将任何可调用对象用作您的哈希函数,无论是普通函数还是函子对象。

Then pass callable object in the constructor: 然后在构造函数中传递可调用对象:

template<class Key, class Value, class Hash>
class hashtable
{
  hashtable(Hash h);
};

This allows you to specify different hash functions without creating new classes. 这使您可以指定不同的哈希函数,而无需创建新类。

Finally, to make declaration and construction of hashtable s more convenient, we specify default template parameters and constructor arguments: 最后,为了使hashtable的声明和构造更加方便,我们指定默认模板参数和构造函数参数:

template<class Key, class Value, class Hash = std::hash<Key> >
class hashtable
{
  hashtable(Hash h = Hash());
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM