【问题标题】:virtual int operator()(int k);虚拟 int 运算符()(int k);
【发布时间】:2013-11-23 16:56:06
【问题描述】:

在标题中:

#include <iostream>
#include <vector>
using namespace std;

template<class Key>
class HashFunction{
public:
    int N;
    virtual int operator()(Key k)=0;
};

class MyHashFunction : public HashFunction <int> {
public:
    virtual int operator()(int k);

};

然后在cpp文件中:

#include "Hash classes.h"

int MyHashFunction::operator ()(int k){
    return k% this->N ;
}

谁能解释一下这个语法: virtual int operator()(Key k)=0; 我了解虚拟方法和'= 0'以及模板是什么......一般来说,但我无法弄清楚这个“int operator()(Key k)”的含义以及它在cpp文件中的使用方式, 我在 c++ 中使用这些概念还没有太多经验,所以语法很烦人

感谢您的宝贵时间,非常感谢。

【问题讨论】:

  • C++ 的这个特性称为“运算符重载”。 operator()(运算符圆括号)在这种情况下。谷歌它以获取更多信息。

标签: c++ visual-c++


【解决方案1】:

您为对象 MyHashFunction 定义 operator(),这意味着您可以像调用函数一样调用实例。

例如

MyHashFunction myHashFunctionInstance;
myHashFunctionInstance(20); //Call the operator()

【讨论】:

    【解决方案2】:

    这只是重载函数调用运算符的虚拟版本,即()-运算符。

    例如:

    void foo(Base const & x)
    {
        int n = x(1, 2, 3);    // calls int Base::operator()(int, int, int),
                               // which may be virtual and dispatched dynamically
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多