本文介绍了我怎么能在std :: vector中使用前向声明的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为您只能创建对向前声明的类的引用或指针成员.但是,我惊讶地发现了这个作品:

I thought that you could only create a reference or pointer member to a forward-declared class. However, I was surprised to discover this works:

#include <vector>

struct Donkey;

struct Cage
{
    std::vector<Donkey> donkeys;
};

struct Donkey
{
};

int main()
{
    Cage c;
}

http://ideone.com/EP0zKR

为什么用向前声明的类定义 std :: vector ?这是标准吗?

How come std::vector can be defined with a forward-declared class? Is this standard?

推荐答案

实际上,您不能.

仅仅因为您的程序编译(取决于底层实现的事实)并不意味着它是有效的.

Just because your program compiles (which is down to facts of the underlying implementation) does not mean it is valid.

除了声明 T * T& ,您可以在其中使用前向声明;只是这不是其中一个.

There are times other than declaring a T* or a T& at which you may use a forward declaration; it's just that this is not one of them.

这篇关于我怎么能在std :: vector中使用前向声明的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 01:55