difference between pointer and reference in c?

前端 未结 9 1520
傲寒
傲寒 2020-12-25 08:11

what is the difference between pointer , reference and dereference in c?

9条回答
  •  温柔的废话
    2020-12-25 09:00

    According to my experience, let me answer.

    In C++, there are variables (normal variables, pointer variables, etc.) and references.

    The compiler will assign an address to each variable. Obviously, the address of this variable cannot appear the same. It can be said that each variable is actually an address. What is the reference &, the reference is not a variable but a tag, so the compiler will not assign him an address, but it does not mean that it has no address, its address is the address of the variable or object it refers to, so it is used as a tag Used to set its address to the address of the variable or object it refers to when the compiler parses it. This creates a situation where the address is the same as the address of the variable or object it references, unbelief Can compile and ponder or try GDB!

    Since the reference and the address of the object it refers to are the same, why should C++ introduce the concept of reference? The pointer can also achieve the goal, it is not an extra move. I say it's the main reason I think!

    For consistency and consistency! for example:

    class box {
     private:
      int l;
    
     public:
      box(int length = 0) : l(length){};
      box operator+(const box& that) {
        box b;
        b.l = this->l + that.l;
        return b;
      }
      box operator+(const box* that) {
        box b;
        b.l = this->l + that->l;
        return b;
      }
    };
    
    int main() {
      box b1(2);
      box b2(4);
    
      box b3 = b1 + b2;
      box b4 = b1 + &b2;
    
      return 0;
    }
    

    Above I overloaded the + operator of the box object, using references and pointers as arguments. In the main two expressions are not written in the same way, both can achieve the same function, obviously using the way of reference can be convenient to express, the use of pointers is more complicated, in the case of a large amount of code, you may be this Things get dizzy. If you think there are more important reasons, please let me know by comment!

提交回复
热议问题