将复杂对象传递给 c++ 中的函数,但数组订阅运算符无法正常工作
Passing a complex object to a function in c++ but array subscription operator is not working properly
>我在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
相关文章:
- 布尔比较运算符是如何在C++中工作的
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 让类与运算符一起工作更简单的方法
- 枚举运算符不工作
- 返回对象如何与分配运算符一起工作
- C++:成员二进制加运算符的工作原理
- 排序向量<变体<...>>无法通过运算符正常工作<
- 当我们有数字和字符串时,>>运算符如何工作
- std::string 赋值运算符如何工作
- 位移位运算符不工作
- 赋值运算符不工作
- C++ == 运算符不工作
- 为什么我的超载<<运算符不工作?
- 重载运算符 [] 如何工作
- 复制构造函数未被调用,无法理解赋值运算符的工作方式
- 为什么std::字符串串联运算符的工作原理类似于右关联运算符
- cout 的<<运算符如何根据运算符优先级工作
- "Or"运算符如何工作?(C++)
- ifstream提取运算符不工作
- 为什么不允许指针的运算符重载工作?