浙大 C++ 课程学习笔记4 - 引用

94 阅读1分钟

浙大 C++

网易云课堂-C++

引用

  • 放对象的地方
    • 堆栈
    • 全局数据区
  • 访问对象的方式
    • 变量访问
    • 指针访问
    • 引用访问
  1. declaring references

references are a new data type in c++

char c; // a char
char* p = &c; // a pointer to a char
char& r = c;  // a reference to a char 相当于给c起别名,修改r或c会互相影响

image.png

  1. Reference

declares a new name for an existing object

int x = 47;
int& y = x; // y is a reference to x

// x and y now refer to the same variable
cout << y; // 47
y = 3;
cout << x; // 3
  1. rules of references
  • references must be initialized when defied.
  • initialization establishes a binding

In declaration

int x = 3;
int& y = x;
const int& z = x; // 不能通过z修改值,但通过x和y依然可以修改

As a function argument

void f(int& i);

int y = 0;
f(y);
  • Bindings don't change at run time, unlike pointers
  • Assignment changes the object referred-to
  • The target of a reference must have a location!
void f(int& i);

int y = 0;
f(y * 2); // warning or error
  1. 案例
int* f(int* x){
    (*x)++;
    return x; // safe , x is outside this scope
}

int& g(int& x){
    x++; // same effect as in f()
    return x; // safe , x is outside this scope
}

int z;

int& h(){
    int q;
    //return q; // Error
    return z; // safe , z lives outside this scope
}

int main(){
    int a = 0;
    f(&a);  // Ugly, but explicit
    g(a);   // Clean, but 
    h() = 16;
    cout << z;
}
  1. pointers vs. references

image.png

image.png


思考拓展:与java的区别和相似点