使用未定义类型 [英] Use of undefined type
问题描述
#include <iostream>
class Core;
class State;
int main (){
std::cin.get();
return 0;
}
class State{
public:
State(Core* core){
core->setState();
}
};
class Core{
public:
Core(){
State state(this);
}
void setState(){
std::cout << "setting state" << std::endl;
}
};
我得到使用未定义类型错误。我想如果我转发声明这两个类,它会解决这个问题,但我不能弄清楚。它是只是愚蠢的c ++语法,我错过了?
I keep getting the "use of undefined type" error. I thought that if I forward declare both of the classes, it would fix the problem but I can't figure it out. Is it just silly c++ syntax that I'm missing?
编辑:对不起的gamestate打字错误,我把它改为状态,它仍然产生错误。 / p>
Sorry about the gamestate typo, I've changed it to State and it still produces the error.
推荐答案
在 State :: State
,您使用 Core
。您可以在您的示例中轻松修复此问题:
In State::State
, you are using Core
before it is actually defined. You can fix this easily in your example:
class State{
public:
State(Core* core);
};
class Core{
// This stays the same...
};
State::State(Core* core)
{
core->setState();
}
在实践中更常见的是将这些函数实现为单独的实现( .cpp
)文件,在这种情况下,转发声明将按照您的预期工作。
It's much more common in practice to have the implementation of these functions in a separate implementation (.cpp
) files, in which case the forward declarations would work as you've expected.
那种情况:
// State.h
class Core
class State{
public:
State(Core* core);
};
并
// Core.h
#include "State.h"
class Core{
public:
Core(){
State state(this);
}
void setState(){
std::cout << "setting state" << std::endl;
}
};
和实现文件:
// State.cpp
#include "State.h"
#include "Core.h"
State::State(Core* core)
{
core->setState();
}
这篇关于使用未定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!