gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:39:02 74 4
gpt4 key购买 nike

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

#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/

74 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com