点运算符和箭头运算符之间的区别 结构对象变量 在 C 或 C++ 中创建树

difference between the dot operator and arrow operator by structure object variable for tree creation in c or c++

本文关键字:运算符 C++ 创建 变量 结构 之间 点运算 区别 对象      更新时间:2023-10-16

我必须澄清一个在 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更具可读性的等价物。

当您有指向结构实例的指针时,可以使用箭头运算符:->

当您具有结构的变量或直接实例时,可以使用点运算符.

在这些情况下,如果成员具有正确的可访问性,将以相同的方式访问类。