这是一个错字还是我错过了什么?

For*_*ent 4 c++ constructor c++11

美好的一天,我正在讨论Bjarne Stroustrup的"C++编程语言",我正面临一段代码,我认为这些代码应该是非法的,但是在文中提出.

我想知道这是否只是一个轻微的疏忽,或者是否有一些我遗漏的东西.

从第3章第63页开始:我们有用户定义的类型Vector,如下所示:

class Vector {
    private:
    double* elem; // elem points to an array of sz doubles
    int sz;

    public:
    Vector(int s) :elem{new double[s]}, sz{s} // constructor: acquire resources
    {
            for (int i=0; i!=s; ++i) elem[i]=0; // initialize elements
    }

    Vector(std::initializer_list<double>)
    {
    // initialize with a list
    } 
    // ...
    void push_back(double)
    { 
    // add element at end increasing the size by one
    }

    ~Vector() {
     delete[] elem; 
     } // destructor: release resources

    double& operator[](int i);

    int size() const;
    };
Run Code Online (Sandbox Code Playgroud)

注意Vector有2个构造函数,一个只有size,另一个有一个完整的初始化列表,看起来像{2.0,3.1,4}

现在我们继续定义一个名为"Container"的抽象类,它看起来像这样:

class Container {
    public:
    virtual double& operator[](int) = 0; // pure virtual function
    virtual int size() const = 0; // const member function (pure virtual) 
    virtual ~Container() {} // destructor 
    };
Run Code Online (Sandbox Code Playgroud)

在这一点上,Bjarne希望通过定义一个继承自Container的具体类来展示Container的"抽象性",并且碰巧使用Vector字段进行内部使用.这里是:

    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(); }
      };
Run Code Online (Sandbox Code Playgroud)

注意Vector_container在内部使用Vector对象.这个类只有一个显式构造函数,它接受容器的大小(并使用该大小传递其内部Vector的构造函数).

现在回想起Vector还有另一种形式的构造函数:Vector(std :: initializer_list)

这一切都很好,花花公子但令我困惑的是,教科书继续提出这段代码:

 void g()
 {
     Vector_container vc {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
     // use vc as a Container type
 }
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,vc是Vector_container的一个实例,正在将初始化列表传递给它的构造函数.这让我很困惑.Vector_container的定义中没有提到这样的构造函数.

我在这里想念的是什么?谢谢

Gam*_*per 6

也许是对书作家的疏忽.自己创建构造函数应该没有问题:

class Vector_container : public Container {
public:
    //...
    Vector_container( std::initializer_list< double> a)
        :v(a){
    }
    //...
}
Run Code Online (Sandbox Code Playgroud)

你实际上是正确地说这本书上缺少某些东西.