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;}
新闻热点
疑难解答