点运算符和箭头运算符之间的差异由结构对象变量用于c或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 left = NULL; tree ->right = NULL; tree -> symbol = storesym[i]; tree -> freq = storefreq[i]; tree -> flag = 0; tree -> next = i + 1; cout<<"check1 : "< 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)它们如何在内存中分配?
这个.
operator期望它的操作数是struct ...
或union ...
类型的表达式。 ->
运算符期望其操作数是“指向struct ...
指针”或“指向union ...
指针”的表达式。
表达式tree
具有类型“指向struct Huffman
指针”,因此您使用->
运算符来访问成员。
表达式tree[i]
具有类型“ struct Huffman
”; 下标运算符隐式取消引用指针(记住a[i]
被评估为*(a + i)
),因此你使用.
运营商访问会员。
基本上, a->b
是(*a).b
更具可读性的等价物。
(1): ->
只是(*).
的快捷方式(*).
例如:
string s = "abc"; string *p_s = &s; s.length(); (*p_s).length(); p_s->length(); //shortcut
如果有指向结构实例的指针,则使用箭头运算符: ->
。
如果有结构的变量或直接实例,则使用点运算符.
在这些情况下,类将以相同的方式访问,提供成员具有正确的可访问性。