当编译器编译类User
并进入MyMessageBox
行,MyMessageBox
尚未定义。编译器不知道MyMessageBox
存在,所以不能理解你的类成员的含义。
您需要确保MyMessageBox
被定义为之前您使用它作为成员。这是通过颠倒定义顺序来解决的。但是,您具有循环依赖关系:如果将MyMessageBox
移动到User
以上,则在MyMessageBox
的定义中将不会定义名称User
!
您可以做的是正向声明User
;即声明它,但不要定义它。在编译过程中,声明但未定义的类型称为不完整类型。 考虑简单的例子:
struct foo; // foo is *declared* to be a struct, but that struct is not yet defined
struct bar
{
// this is okay, it's just a pointer;
// we can point to something without knowing how that something is defined
foo* fp;
// likewise, we can form a reference to it
void some_func(foo& fr);
// but this would be an error, as before, because it requires a definition
/* foo fooMember; */
};
struct foo // okay, now define foo!
{
int fooInt;
double fooDouble;
};
void bar::some_func(foo& fr)
{
// now that foo is defined, we can read that reference:
fr.fooInt = 111605;
fr.foDouble = 123.456;
}
向前声明User
,MyMessageBox
仍然可以形成一个指针或引用它:
class User; // let the compiler know such a class will be defined
class MyMessageBox
{
public:
// this is ok, no definitions needed yet for User (or Message)
void sendMessage(Message *msg, User *recvr);
Message receiveMessage();
vector<Message>* dataMessageList;
};
class User
{
public:
// also ok, since it's now defined
MyMessageBox dataMsgBox;
};
您无法做到这一点的其他方式:如前所述,一个班级成员需要有一个定义。 (原因是编译器需要知道多少内存User
如何占用了,要知道,它需要知道其成员的大小。)如果你是在说:
class MyMessageBox;
class User
{
public:
// size not available! it's an incomplete type
MyMessageBox dataMsgBox;
};
这是行不通的,因为它还不知道尺寸。
在一个侧面说明,这样的功能:
void sendMessage(Message *msg, User *recvr);
也许不应该由指针采取这类原因。没有消息就不能发送消息,也不能发送没有用户发送消息的消息。而这两方面的情况是由空作为参数传递给任一参数表达
相反,使用引用(可能是const的)(null是一个完全有效的指针值!):
void sendMessage(const Message& msg, User& recvr);
无尽的时间,我去这个错误,只是意识到由IDE生成的导入警卫重复 – Mazyod 2015-08-15 11:39:22
请注意,如果您将一个外部引用声明放在.h/.hpp文件中也可以得到此错误在定义类之前,即使在.cpp文件中的.h/.hpp包含之后有实际的声明。 – Owl 2016-03-19 20:01:41
@Mazyod。谢谢谢谢。我无法弄清楚是什么造成了这个奇怪的错误。 – 2017-02-10 19:13:04