#include <iostream>
using namespace std;
class CDemo{
private:
const int num;
int & ref;
public:
CDemo(int &n):num(n), ref(n){//引用和常量成员初始化必须赋值,且只能在参数列表中赋值
//num=ref=n
}
void print(){
cout<<"ref值为:"<<ref<<endl;
cout<<"num的值为:"<<num<<endl;
}
};
int main()
{
int a=20;
CDemo demo(a);
demo.print();
return 0;
}//运行结果:
// ref值为:20
//num的值为:20
引用型变量在初始化时,int &n要加引用符号
#include <iostream>
using namespace std
class CDemo{
private:
const int num;
int & ref;
int value;
public:
CDemo(int n,int &b):num(n), ref(b){
}
void print(){
cout<<num<<endl;
cout<<ref<<endl;
}
};
int main(){
int a=56;int d=13;
CDemo c(a,d);
c.print();
return 0;
}
//运行结果
//56
//13;