请考虑以下代码:
#include <iostream>
using namespace std;
class test
{
int& ref;
public:
test(int i):ref(i)
{
cout << "Constructor Called" << endl;
}
void p(){ cout<< ref << "\n";}
};
int main()
{
test obj(5);
obj.p();
return 0;
}
输出:
Constructor Called
5
疑问:如何在此处使用整数值(5)初始化非常量引用(ref),而以下代码失败:
int& r = 5;
test's
构造函数:
test(int i)
以值int
作为参数。
obj
通过传递5
给对象的构造函数来初始化对象时,即:
test obj(5);
将构造函数的参数i
设置为5
(即:5
复制到i
),然后ref
在构造函数成员初始化列表中使用该参数初始化成员引用(而不是5
构造函数调用时使用的文字):
test(int i):ref(i)
您有一个危险的参考:该参考的寿命ref
超过了被参考的对象(i
),因为i
一旦返回构造函数,构造函数的参数将不再存在。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句