私はこのコードを持っています:
#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
ですか?
そして、なぜコンストラクターのX &_x
型のインスタンスでメンバーを初期化するのがエラーではないのですか?X
Y