c++ - 这是错字还是我遗漏了什么?

标签 c++ c++11 constructor

美好的一天,我正在复习 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;
    };

注意 Vector 有 2 个构造函数,一个只有大小,另一个有一个完整的初始化列表,看起来像 {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 
    };

在这一点上,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(); }
      };

请注意,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
 }

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

我在这里错过了什么? 谢谢

最佳答案

也许是对书籍作者的疏忽。不过,您自己创建构造函数应该没有问题:

class Vector_container : public Container {
public:
    //...
    Vector_container( std::initializer_list< double> a)
        :v(a){
    }
    //...
}

您说的确实是书上确实缺少了一些东西。

关于c++ - 这是错字还是我遗漏了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33695435/

相关文章:

c++ - 编译器独立类型

c++ - C++11 中的递归 lambda 函数

c++ - MinGW 4.6.2 std::原子指针

c# - 实例化类的通用字段

c++ - `const` 对象的构造函数

c++ - 文件 I/O 行尾

c++ - 在C#项目中,如何引用用C++编写并用/clr编译的项目?

类构造函数和成员变量(字段)

c++ - 字符串与哈希作为映射键 - 性能

c++ - 为什么 std::move 会阻止 RVO(返回值优化)?