【发布时间】:2013-02-06 13:22:32
【问题描述】:
我有this code:
#include <iostream>
using namespace std;
struct X {
int a = 1;
};
struct Y {
X &_x;
Y(X &x) : _x(x) {}
};
// intentionally typoed version of Y, without the reference in the constructor
struct Z {
X &_x;
Z(X x) : _x(x) {}
};
int main() {
X x;
Y y(x);
Z z(x);
cout << "x: " << &x << endl;
cout << "y.x: " << &y._x << endl;
cout << "z.x: " << &z._x << endl;
}
我一直发现自己忘记了这种格式的类的构造函数中的&。
这会输出以下内容:
x: 0xbfa195f8
y.x: 0xbfa195f8
z.x: 0xbfa195fc
为什么y 和z 的行为不同?
为什么在Y的构造函数中用X类型的实例初始化X &_x成员不会出错?
【问题讨论】: