gpt4 book ai didi

c++ - 为什么带有花括号初始化器列表的构造函数/虚拟析构函数不起作用?

转载 作者:太空狗 更新时间:2023-10-29 23:35:07 24 4
gpt4 key购买 nike

为什么下面的代码不能编译?

#include <vector>

class Foo
{
public:
Foo()
{ }

virtual ~Foo()
{ }

std::vector<int> aVec;
};


Foo bar =
{
{ 1, 2, 3, 4, 5 }
};

编译以下代码时:

#include <vector>

class Foo
{
public:

/*Foo()
{ }

virtual*/ ~Foo()
{ }

std::vector<int> aVec;
};


Foo bar =
{
{ 1, 2, 3, 4, 5 }
};

除了提及语言规则外,请详细说明这些规则背后的基本原理。

为什么constructor和virtual destructor的存在会停止初始化?

最佳答案

因为 Foo 是类类型,所以大括号初始化列表被视为 aggregate initialization .除其他外,这要求该类没有显式构造函数或虚拟成员:

Aggregate initialization is a form of list-initialization, which initializes aggregates. An aggregate is one of the following types:

class type (typically, struct or union), that has...

  • no private or protected non-static data members

  • no user-provided, inherited, or explicit (since C++17) constructors (explicitly defaulted or deleted constructors are allowed)

  • no virtual, private, or protected base classes
  • no virtual member functions
  • default member initializers

关于c++ - 为什么带有花括号初始化器列表的构造函数/虚拟析构函数不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47577229/

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