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

Passing a complex object to a function in c++ but array subscription operator is not working properly

本文关键字:运算符 常工作 工作 数组 对象 复杂 c++ 函数      更新时间:2023-10-16

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

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

其中哈希映射的键类型为"无符号字符数组",值为类型为"int"。我需要将此对象传递给函数 hMap_receive((,并且应该能够持有对象的所有权,即 hMap_receive(( 应该能够修改对象 hMap 的内容。

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

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