2010-12-16 100 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