簡體   English   中英

C ++成員變量混淆

[英]C++ Member variables confusion

我正在學習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所指。 z是駐留在FooBar大小的內存塊; 為了合法地聲明一個這樣的成員變量,必須將Bar的完整定義放在Foo之前,以便編譯器知道Bar大小。

zBar的實例,並且必須在Foo是時構造,因此:

class Foo {
public:
    Foo(…)
        : x(<instance of or reference to Bar>),
          y(<pointer to Bar>), // optional
          z(<Bar ctor params>)
    { … }

請注意, xz必須在構造期間初始化,而省略y的初始化是合法的(盡管有問題)。

z與父Foo實例占用相同的內存,但這是Bar的實例,而不僅僅是Bar大小的內存塊。

  1. 是的,它是一個條形圖: zBar類型的標識符。 如果尚未定義默認構造函數,則將生成編譯器錯誤(編譯器通常會執行此操作,但如果您定義了至少一個構造->構造器,則不會這樣做)。
  2. 是的,它是條形大小的內存塊,在分配Foo分配。

是酒吧嗎? 如果是這樣,怎么給它Bar的唯一構造函數呢?

是的,z是一個小節。 如果Bar沒有默認構造函數,則必須在Foo member initializers list初始化Bar 下面的示例忽略x,y初始化:

Foo::Foo(int param1, int param2, int param3)
: z(param1, param2, param3)
{
}

是否可以將屬於Foo實例的Bar大小的內存塊初始化為Bar?

是的,Bar對象在Foo對象內部對齊

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM