首页 > 学院 > 开发设计 > 正文

Reference:alias

2019-11-11 07:07:19
字体:
来源:转载
供稿:网友

Rule:

1.References must be initialized when defined. Initialization establishes a binding.

eg: type& refname = name; //thus the value of refname is the same as name.

2.Bindings don’t change at run time, unlike pointers.

3.The target of a reference must have a location! 

 eg:void func(int &); //automatically binding when call the function.

func(i*3); //warning or error!

 Restrictions:

1.No references to refercences

2.No pointers to references

int & * p; //illegal

  But reference to pointer is ok

int* & p;

3.No arrays of reference

Notice: constant value can be modified through reference.

#include <iostream>using namespace std;int main(){    int& *p;    int x=3;    int &y=x;    const int&z=x;    cout<<"z:"<<z<<endl;    y=4;    cout<<"after y=4,z:"<<z<<endl;    x=5;    cout<<"after x=5,z:"<<z<<endl;//error here:z cannot be assigned,but it still can be modified by y or x.//  z=5;    return 0;}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表