出于教学原因,让我们尝试编译这段代码:
class Bar {
public:
Bar(int bunchOfCrap, int thatNeedsToBeHere, double toMakeABar);
};
class Foo {
public:
Bar &x; // <- This is a ref, Bar is not instantiated (this is just a placeholder)
Bar *y; // <- This is a pointer, Bar is not instantiated (this is just a *safer* placeholder)
Bar z; // <- What is this???
};
int main() {
Foo foo;
}
输出:
c++ uuu.cpp -o uuu
uuu.cpp:10:7: error: implicit default constructor for 'Foo' must explicitly initialize the reference member 'x'
class Foo {
^
uuu.cpp:14:10: note: declared here
Bar &x; // <- This is a ref, Bar is not instantiated (this is just a placeholder)
^
uuu.cpp:10:7: error: implicit default constructor for 'Foo' must explicitly initialize the member 'z' which does not
have a default constructor
class Foo {
^
uuu.cpp:16:9: note: member is declared here
Bar z; // <- What is this???
^
uuu.cpp:2:7: note: 'Bar' declared here
class Bar {
^
uuu.cpp:21:9: note: implicit default constructor for 'Foo' first required here
Foo foo;
^
2 errors generated.
make: *** [uuu] Error 1
正如它所说,您必须同时初始化成员引用Bar &x和成员变量Bar z;,因为Bar没有默认构造函数。y不必初始化,默认为NULL.
两者x和y间接地指代对象。您无法更改x所指的内容(因此必须在实例化时对其进行初始化Foo)。您可以更改y所指的内容。z是一个Bar大小的内存块,位于内部Foo;为了让你像这样合法地声明一个成员变量,你必须把Barbefore的完整定义放好,Foo以便编译器知道有多大Bar。