代码之家  ›  专栏  ›  技术社区  ›  Sss

c或c++中树创建的结构对象变量点运算符和箭头运算符之间的差异[重复]

c c++
  •  0
  • Sss  · 技术社区  · 10 年前

    我必须澄清一个疑问,它在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) 它们在内存中是如何分配的?

    3 回复  |  直到 10 年前
        1
  •  4
  •   yizzlez    10 年前

    (1) : -> 只是一条捷径 (*). 例如:

    string s = "abc";
    string *p_s = &s;
    s.length();
    (*p_s).length(); 
    p_s->length(); //shortcut
    
        2
  •  1
  •   John Bode    10 年前

    这个 . 运算符要求其操作数为类型的表达式 struct ... union ... 这个 -> 运算符要求其操作数为“pointer to”类型的表达式 结构。。。 “或”指针指向 协会 ".

    表达式 tree 具有类型“pointer to” struct Huffman “,所以您使用 -> 操作员访问成员。

    表达式 tree[i] 具有类型“ 结构霍夫曼 “;下标运算符隐式取消引用指针(请记住 a[i] 评估为 *(a + i) ),所以您使用 . 操作员访问成员。

    大体上 a->b (*a).b .

        3
  •  1
  •   Thomas Matthews    10 年前

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

    当您有一个结构的变量或直接实例时, .

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