c++ - 为什么我可以在 std::vector 中使用前向声明的类?

标签 c++

我认为您只能创建指向前向声明类的引用或指针成员。然而,我惊讶地发现这个有效:

#include <vector>

struct Donkey;

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

struct Donkey
{
};

int main()
{
    Cage c;
}

http://ideone.com/EP0zKR

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

最佳答案

实际上,你不能。

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

There are times other than declaring a T* or a T& at which you may use a forward declaration ;就是那个this is not one of them .

关于c++ - 为什么我可以在 std::vector 中使用前向声明的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29262292/

相关文章:

c++ - 初始化列表问题,重点是std vector

java - 如何从虚拟机调用 native 函数?

c++ - boost 正则表达式捕获组并替换

c++ - 我可以使用 std::vector<std::vector<T>> 来表示 C++ 中的二维数组吗?

c++ - 在命名空间中使用指令和函数重载

c++ - 将 C 数组分配给 C+ +'s std::array? (std::array<T,U> = T[U]) - no suitable constructor exists from "T [U ]"to "std::array<T,U>"

c++ - Makefile 忽略命令 export OMP_NUM_THREADS

c++ - 通过它的质心提取对象

c++ - 基于泰勒级数的基于模板的 Sin() 实现产生不正确的结果 C++

c++ - Qt Quick 2 iOS 缺口回避