为什么不能为std :: vector使用forward声明?

为什么不能为std :: vector使用forward声明?

问题描述:

如果我创建这样的类:

// B.h
#ifndef _B_H_
#define _B_H_

class B
{
private:
    int x;
    int y;
};

#endif // _B_H_

p>

and use it like this:

// main.cpp
#include <iostream>
#include <vector>

class B; // Forward declaration.

class A
{
public:
    A() {
        std::cout << v.size() << std::endl;
    }

private:
    std::vector<B> v;
};

int main()
{
    A a;
}

编译器在编译 main.cpp 。现在我知道的解决方案是 #includeB.h,但我很好奇为什么它失败。 g ++ cl 的错误消息在这件事上非常有启发性。

The compiler fails when compiling main.cpp. Now the solution I know is to #include "B.h", but I'm curious as to why it fails. Neither g++ or cl's error messages were very enlightening in this matter.

编译器需要知道大B是什么,才能生成适当的布局信息。如果相反,你说 std :: vector< B *> ,那么编译器不需要知道大B是多大,因为它知道指针有多大。

The compiler needs to know how big "B" is before it can generate the appropriate layout information. If instead, you said std::vector<B*>, then the compiler wouldn't need to know how big B is because it knows how big a pointer is.