gpt4 book ai didi

c++ - 有人给我一个使用 QVector::QVector(std::initializer_list args) 的例子吗?

转载 作者:可可西里 更新时间:2023-11-01 18:26:38 29 4
gpt4 key购买 nike

谁能给我一个使用以下构造函数 int Qt 的例子?

QVector::QVector(std::initializer_list<T> args);

最佳答案

采用 std::initializer_list 的构造函数使用列表初始化时会考虑。这是一个涉及花括号初始化列表的初始化:

QVector<int> v{1, 2, 3, 4, 5};
// or equivalently
QVector<int> v = {1, 2, 3, 4, 5};

请注意,这是 C++11 的特性。事实上,第一种语法是 C++11 的新语法,而第二种语法可以在 C++03 中用于聚合初始化。

您还可以使用直接初始化并将初始化列表作为参数传递:

QVector<int> v({1, 2, 3, 4, 5});

因为构造函数不是explicit , 它也可以用于其他一些有趣的方式:

  1. 传递 QVector参数:

    void foo(QVector<int>);

    foo({1, 2, 3, 4, 5});
  2. 返回 QVector :

    QVector<int> bar()
    {
    return {1, 2, 3, 4, 5};
    }

§8.5.4 列表初始化 [dcl.init.list]:

A constructor is an initializer-list constructor if its first parameter is of type std::initializer_list<E> or reference to possibly cv-qualified std::initializer_list<E> for some type E, and either there are no other parameters or else all other parameters have default arguments (8.3.6).

§13.3.1.7 通过列表初始化 [over.match.list] 进行初始化:

When objects of non-aggregate class type T are list-initialized (8.5.4), overload resolution selects the constructor in two phases:

  • Initially, the candidate functions are the initializer-list constructors (8.5.4) of the class T and the argument list consists of the initializer list as a single argument.

  • [...]

关于c++ - 有人给我一个使用 QVector::QVector(std::initializer_list<T> args) 的例子吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15641318/

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