簡體   English   中英

C ++類成員

[英]C++ class members

我從Java到C ++ ...

當我嘗試這樣做時...

class Box {
    Table* onTable;
};

class Table {
    Box* boxOnIt;
};

int main() {
    Table table;
    Box box;

    table.boxOnIt = &box;
    box.onTable = &table;

    return 0;
}

編譯器告訴我Table是未定義的。 如果我切換類定義,則編譯器會告訴我Box未定義

在Java中,我可以毫無問題地執行類似的操作。 有解決方案嗎? 謝謝...

您應該使用前向聲明 只需將此作為您的第一條聲明即可:

class Table;  // Here is the forward declaration

在班級框前添加以下內容:

class Table;

因此,您可以向前聲明類Table,以便可以在Box中使用指向它的指針。

您在這里有一個循環依賴關系,需要轉發聲明其中一個類:

// forward declaration
class Box;

class Table
{
    Box* boxOnit;
}  // eo class Table

class Box
{
    Table* onTable
} // eo class Box

請注意,通常來說,對於BoxTable ,我們將有一個單獨的頭文件,在這兩個文件中都使用前向聲明,例如:

class Table;

class Box
{
    Table* table;
}; // eo class Box

table.h

class Box;

class Table
{
    Box* box;
};  // eo class Table

然后,在我們的實現(.cpp)文件中包括必要的文件:

box.cpp

#include "box.h"
#include "table.h"

table.cpp

#include "box.h"
#include "table.h"
class Table;

class Box {
    Table* onTable;
};

class Table {
    Box* boxOnIt;
};

int main() {
    Table table;
    Box box;

    table.boxOnIt = &box;
    box.onTable = &table;

    return 0;
}

您應該向前聲明兩個類之一:

class Table; // forward declare Table so that Box can use it.

class Box {
    Table* onTable;
};

class Table {
    Box* boxOnIt;
};

int main() {
    Table table;
    Box box;

    table.boxOnIt = &box;
    box.onTable = &table;

    return 0;
}

或相反亦然:

class Box; // forward declare Box so that Table can use it.

class Table {
    Box* boxOnIt;
};

class Box {
    Table* onTable;
};

int main() {
    Table table;
    Box box;

    table.boxOnIt = &box;
    box.onTable = &table;

    return 0;
}

使用前向聲明,以便第一個聲明的類知道第二個。 http://www.eventhelix.com/realtimemantra/headerfileincludepatterns.htm

在頂部添加類定義

class Table;

class Box {
    Table* onTable;
};

class Table {
    Box* boxOnIt;
};

暫無
暫無

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

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