定义向量类型时向前声明错误? [英] Forward declaration error when defining a vector type?

查看:232
本文介绍了定义向量类型时向前声明错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图尽可能多地使用转发声明,以尽可能减少编译时间。我注意到,当我转发声明一个类,使用像std :: vector作为成员对象(这里的例子):

I'm trying to use forward declarations as much as I can to minimize compilation time. I noticed that when I forward declare a class that is using something like std::vector as a member object (example here):

class myTypeA
class A
{
  A(){};
  ~A(){};
  std::vector<myTypeA > getTypeA();

}

我收到以下错误:

microsoft visual studio 9.0\vc\include\vector(1112) : error C2036: 'myTypeA *' : unknown size
1>        c:\program files\microsoft visual studio 9.0\vc\include\vector(1102) : while compiling class template member function 'bool std::vector<_Ty>::_Buy(unsigned int)'
1>        with
1>        [
1>            _Ty=myTypeA
1>        ]
1>        d:\cpp\A.h(15) : see reference to class template instantiation 'std::vector<_Ty>' being compiled
1>        with
1>        [
1>            _Ty=myTypeA
1>        ]

这是工作正常,当我使用#includemyTypeA.h,为什么? p>

this is working fine when I use the #include "myTypeA.h", why ?

推荐答案

这是因为编译器需要知道要存储在向量中的类型的大小。没有完整的类定义它没有办法知道这一点。

This is because the compiler needs to know the size of the types to be stored in the vector. Without the full class definition it has no way of know this.

另一种方法是存储指向你的前向声明类型的指针 - 但是你需要管理内存分配和释放。

An alternative would be to store pointers to your forward-declared type - however you would need to manage the memory allocation and deallocation.

第三个选项是根据您声明的类型和存储声明一个 shared_ptr 这些在您的矢量。

A third option would be to declare a shared_ptr type based on your forward declared type and store these in your vector.

这篇关于定义向量类型时向前声明错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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