C++成员变量混淆

标签 c++

我正在学习 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

xy 都间接引用对象。您无法更改 x 所指的内容(因此必须在实例化 Foo 时对其进行初始化)。您可以更改 y 所指的内容。 zBar 大小的内存块,位于 Foo 中;为了合法地声明这样的成员变量,您必须将 Bar 的完整定义放在 Foo 之前,以便编译器知道 Bar 有多大> 是。

关于C++成员变量混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14867156/

相关文章:

c++ - 如何在 wxWidgets(C++ 代码)中使用 wxListCtrl 向第二列添加值?

c++ - llvm-ld 仍然存在于 clang 3.4 吗?

c++ - 游戏中的屏幕滚动

c++ - <eof> 附近的 lua 函数参数

c++ - 为什么在使用带有接口(interface)指针的多态行为时没有调用析构函数?

javascript - Qt:如何使用从 evaluateJavaScript 返回的 QVariant?

c++ - 如何改进基于sse的矩阵乘法

c++ - 推导具有不同值类型的映射的返回类型

c++ - C++ 中类似 GameMaker 的功能

C++多线程Windows GUI(访问表单)