在 C++ 中使用 Initializer 列表进行抽象类型初始化

Abstract Type Initialization using Initializer list in C++

我开始阅读 Bjarne Struoustrup 的书 'The C++ Programming Language - 4th Edition',发现以下示例有点令人困惑(抽象类型 - 第 66 页):

class Container {
public:
    virtual double& operator[](int) = 0; // pure virtual function
    virtual int size() const = 0; // const member function (§3.2.1.1)
    virtual ~Container() {} // destructor (§3.2.1.2)
};

class Vector_container : public Container { // Vector_container implements Container
Vector v;
public:
    Vector_container(int s) : v(s) { } // Vector of s elements
    ~Vector_container() {}
    double& operator[](int i) { return v[i]; }
    int size() const { return v.size(); }
};

客户代码:

void use(Container& c)
{
    const int sz = c.size();
    for (int i=0; i!=sz; ++i)
    cout << c[i] << '\n';
}

void g()
{
    Vector_container vc {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
    use(vc);
}

我们在 Vector_container 的 class 声明中没有遗漏以下构造函数吗?

Vector_container(std::initializer_list<double> s) : v(s) { } // Vector of s elements

如果我有什么误解,请指正。

Are we not missing the following constructor in the class declaration of Vector_container?

Vector_container(std::initializer_list<double> s) : v(s) { } // Vector of s elements

你当然是对的。

LIVE

error: no matching constructor for initialization of 'Vector_container'
Vector_container vc {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};

LIVE with ctor taking initializer_list as parameter