C ++类使用未定义类型 [英] C++ class use of undefined type

查看:654
本文介绍了C ++类使用未定义类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,我做,我使用在线程上面的类。即使我在顶部做了一个类的原型仍然抛出那些错误
错误C2027:使用未定义的类型'foo'

  class foo; 

DWORD WINAPI demo(LPVOID param)
{
foo a;
}


class foo
{
public:
int x;
};


解决方案



类的原型


使用向前声明的类,你可以创建指针和类的引用。这是因为指针/引用在所有类/ structs / etc中表示相同。他们都是记忆的地址。因此,例如,您可以创建第二个类,它可以在完全定义类之前接受或包含指针或引用,例如:

  class Bar 
{
private:
foo * aFoo;
public:
Bar(foo * foo2):aFoo(foo2){}
};但是,在编译器看到类的完整定义之前,您必须先完成 不能实例化它。否则编译器不知道要分配多少内存,以及如何调用构造函数和其他方法。在大多数情况下,C ++期望事物在使用之前被定义。转发声明允许你绕过这一点,因为任何类的指针和引用是相同的。因此,您可以向编译器承诺,稍后您将完全定义它。


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.

这篇关于C ++类使用未定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆