我正在学习 C++(来自 Java),这让我很烦,说我有...
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 another placeholder)
Bar z; // <- What is this???
};
class Bar {
public:
Bar(int bunchOfCrap, int thatNeedsToBeHere, double toMakeABar);
};
在此示例中,Bar 有一个构造函数需要指定一组字段才能创建“Bar”。 x 和 y 都不会创建 Bar,我知道 x 创建了一个可以指向 Bar 的引用,而 y 创建了一个也可以表示 Bar 的指针。
我不明白 z 到底是什么。
它是酒吧吗?如果是这样,如何为其指定 Bar 的唯一构造函数?
是否属于 Foo 实例的 Bar 大小的内存块可以初始化为 Bar?
还是别的什么?
谢谢!
最佳答案
出于教学原因,让我们尝试编译这段代码:
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
中;为了合法地声明这样的成员变量,您必须将 Bar
的完整定义放在 Foo
之前,以便编译器知道 Bar
有多大> 是。
关于C++成员变量混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14867156/