2010-12-16 123 views
1

我來從Java到C++ ...C++類成員

當我試圖做到這一點...

class Box { 
    Table* onTable; 
}; 

class Table { 
    Box* boxOnIt; 
}; 

int main() { 
    Table table; 
    Box box; 

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

    return 0; 
} 

編譯器告訴我,表是不確定的。 如果我切換類定義編譯器告訴我,框未定義

在java中,我能夠做到這樣沒有問題。 有沒有解決這個工作? 謝謝...

+0

我覺得有趣的是,沒有答案提到你應該聲明你的屬性是公開的,如果你需要從課堂外訪問它們。類成員在C++中是隱式私有的,因此當你試圖訪問'boxOnIt'或'onTable'時,你應該從代碼中得到編譯器錯誤。 – Kleist 2010-12-16 17:29:28

回答

2

你有一個循環依賴這裏和需要轉發申報的一類:

// forward declaration 
class Box; 

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

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

需要注意的是,一般來講,我們不得不爲BoxTable單獨的頭文件,使用前在雙方的聲明,如:

box.h

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" 
+0

非常感謝,現在代碼正在工作。 – Mustafa 2010-12-16 11:05:11

2

你應該使用forward declarations。剛剛提到這一點作爲你的第一條語句:

class Table; // Here is the forward declaration 
+1

,並使其爲每個對象創建一個單獨(標題)文件的習慣。 box.h和table.h並將它們包含在main.cpp中 – RvdK 2010-12-16 10:52:01

2

類箱前補充一點:

class Table; 

因此,你forward declare類表,這樣指向它可以在框中使用。

1
class Table; 

class Box { 
    Table* onTable; 
}; 

class Table { 
    Box* boxOnIt; 
}; 

int main() { 
    Table table; 
    Box box; 

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

    return 0; 
} 
1

你應該轉發聲明兩個類中的一個:

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; 
} 
0

添加類定義頂部

class Table; 

class Box { 
    Table* onTable; 
}; 

class Table { 
    Box* boxOnIt; 
}; 
+1

這是您在頂部需要的聲明,而不是定義。 – Kleist 2010-12-16 17:26:28