点运算符和箭头运算符之间的区别 结构对象变量 在 C 或 C++ 中创建树
difference between the dot operator and arrow operator by structure object variable for tree creation in c or c++
我必须澄清一个在 c 和 c++ 中也有相同概念的疑问。
假设我有一个这样的结构:
struct Huffman
{
int value;
unsigned char sym; /* symbol */
struct Huffman *left,*right; /* left and right subtrees */
};
typedef struct Huffman Node;
Node * tree;
现在我使用树变量创建树。然后同时使用点运算符和箭头运算符。喜欢这个。
Arrorw 运算符:
for (i = 0; i < data_size; i++)
{
// the problem is here this tree pointer don't store the values for all alphabets, it just remembers the last executed alphabet after this for loop.
tree -> left = NULL;
tree ->right = NULL;
tree -> symbol = storesym[i];
tree -> freq = storefreq[i];
tree -> flag = 0;
tree -> next = i + 1;
cout<<"check1 : "<<tree -> symbol<<endl;
}
点运算符:
for (i = 0; i < data_size; i++)
{
tree[i].symbol = storesym[i];
tree[i].freq = storefreq[i];
tree[i].flag = 0;
tree[i].left = tree[i].right = tree[i].value = NULL;
tree[i].next = i + 1;
}
现在我无法理解(1)两者有什么区别?(2) 它们如何在内存中分配?
(1):->
只是(*).
的快捷方式 例如:
string s = "abc";
string *p_s = &s;
s.length();
(*p_s).length();
p_s->length(); //shortcut
.
运算符期望其操作数是类型 struct ...
或 union ...
的表达式。 ->
运算符希望其操作数是"指向struct ...
的指针"或"指向union ...
的指针"类型的表达式。
表达式 tree
的类型为"指向struct Huffman
的指针",因此您可以使用 ->
运算符访问成员。
表达式tree[i]
的类型为 " struct Huffman
";下标运算符隐式取消引用指针(请记住,a[i]
的计算结果为 *(a + i)
),因此您可以使用 .
运算符访问成员。
基本上,a->b
是(*a).b
更具可读性的等价物。
当您有指向结构实例的指针时,可以使用箭头运算符:->
。
当您具有结构的变量或直接实例时,可以使用点运算符.
在这些情况下,如果成员具有正确的可访问性,将以相同的方式访问类。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 如何防止clang格式在流运算符调用之间添加换行符<<