c++ - 将复杂对象传递给 C++ 中的函数,但数组订阅运算符无法正常工作

标签 c++ function pointers operator-overloading argument-passing

我在 C++ 项目的源文件中声明了一个名为 hMap 的对象:

dense_hash_map<unsigned char *, int, hash<unsigned char *> > hMap;

HashMap 的键是“unsigned char array”类型,值是“int”类型。 我需要将这个对象传递给函数 hMap_receive() 并且应该能够持有对象的所有权,即 hMap_receive() 应该能够修改对象 hMap 的内容。

问题:我应该把它作为指针传递吗?我通过了检查,但无法调用两个运算符重载方法——数组订阅运算符和赋值运算符(如下所示),它们是类“dense_hash_map”的公共(public)成员。

data_type& operator[](const key_type& key) {       // This is our value-add!
    // If key is in the hashtable, returns find(key)->second,
    // otherwise returns insert(value_type(key, T()).first->second.
    // Note it does not create an empty T unless the find fails.
    return rep.template find_or_insert<DefaultValue>(key).second;
  }

  dense_hashtable& operator= (const dense_hashtable& ht) {
    if (&ht == this)  return *this;        // don't copy onto ourselves
    if (!ht.settings.use_empty()) {
      assert(ht.empty());
      dense_hashtable empty_table(ht);  // empty table with ht's thresholds
      this->swap(empty_table);
      return *this;
    }

示例:

hMap_receive(dense_hash_map<int, unsigned char *, hash<int> > hMap, 
unsigned char *key,int data){
.........
.........
 hMap[key] = data;
 cout << hMap[key];
.........
}

工作正常并将数据分配给键值并打印与键关联的数据。但是,

hMap_receive(dense_hash_map<int, unsigned char *, hash<int> > *hMap, 
unsigned char *key,int data){
    .........
    .........
     hMap[key] = data;
     cout << hMap[key];
    .........
    }

既不分配数据也不在关键处提供数据。而是给出错误:

error: invalid types ‘google::dense_hash_map<unsigned char*, int, 
std::tr1::hash<unsigned char*>, eqstr>*[unsigned char*]’ for array subscript

为什么我用指针传递对象时不能正常工作?如果这不是正确的方法,我应该如何传递对象,以便我能够无误地执行对对象的所有操作,并且能够修改调用函数的原始传递对象。

最佳答案

[]对指针类型有特定的含义。如果x类型为 T * , 然后 x[a]表示 *(x+a) , 结果类型为 T .所以,即使输入 T重载了 []运营商,它没有发挥作用。

因此,错误消息是关于您的 dense_hash_map<> 的事实没有 <<为其定义的运算符。

您想传递对您的 dense_hash_map<> 的引用,而不是它的地址。

hMap_receive(dense_hash_map<unsigned char *, int, hash<unsigned char *> > &hMap, 
             unsigned char *key,int data){
    //...

如果 *,请注意替换与 & .

这允许您通过引用调用传入数据结构的函数。这意味着该函数正在操纵用于调用该函数的对象,而不是拷贝。

dense_hash_map<unsigned char *, int, hash<unsigned char *> > my_map;
//...
hMap_receive(my_map, "foo", 10);
//...my_map may be updated by the function

关于c++ - 将复杂对象传递给 C++ 中的函数,但数组订阅运算符无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19203078/

相关文章:

r - 当结果不明确时如何使用tryCatch

C# 不安全值类型数组到字节数组的转换

c++ - char const * const * - <错误读取字符串的字符>

c++ - 如何使用 boost asio 进行 IP 地址操作(屏蔽、or'ing 等)?

function - 使用百分号作为前缀运算符名称的一部分

C++ iomanip 对齐

c++ - 类内函数

pointers - 修改原始值时更改借用值

c++ - 求组合的几个循环代码如何转化为递归的方法?

c++ - 我将如何在 C++ 中显示我的俄罗斯方 block 桶?