为什么不能为std :: vector使用forward声明? [英] Why can't a forward declaration be used for a std::vector?

查看:194
本文介绍了为什么不能为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.

这篇关于为什么不能为std :: vector使用forward声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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