I have a class that I made that I am using in thread above the class. Even though I did a prototype of the class at the top it still throws off those errors error C2027: use of undefined 开发者_开发知识库type 'foo'
class foo;
DWORD WINAPI demo(LPVOID param)
{
foo a;
}
class foo
{
public:
int x;
};
Even though I did a prototype of the class
With a forward declaration of the class you can create pointers and references to the class. This is because pointers/references are represented the same across all classes/structs/etc. They're all just addresses of memory. So, for example, you could create a second class that can accept or contains pointers or references before fully defining the class, ie:
class Bar
{
private:
foo* aFoo;
public:
Bar(foo* foo2) : aFoo(foo2) {}
};
However, until the compiler sees the full definition of the class, you can't instantiate it. Otherwise the compiler doesn't know how much memory to allocate and how to call the constructor and other methods. In most cases, C++ expects things to be defined before they are used. Forward declaration lets you get around this a little bit because pointers and references for any class are identical. So you can promise to the compiler you'll fully define it later.
精彩评论