【问题标题】:Abstract Type Initialization using Initializer list in C++在 C++ 中使用初始化器列表进行抽象类型初始化
【发布时间】:2016-05-21 23:36:00
【问题描述】:

我开始阅读 Bjarne Struoustrup 的《C++ 编程语言 - 第 4 版》一书,发现以下示例有点令人困惑(抽象类型 - 第 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的类声明中我们是不是少了下面的构造函数?

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

如果我在这里误解了任何内容,请纠正我。

【问题讨论】:

  • 本书有勘误表吗?
  • 第 4 版 (stroustrup.com/4th.html) 网上只有一个勘误表。有人可以将 Bjarne 的注意力引向这篇文章。

标签: c++ c++11 constructor initializer-list


【解决方案1】:

我们在类声明中是不是缺少下面的构造函数 Vector_container 的?

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

你当然是对的。

LIVE

错误:没有匹配的构造函数用于初始化 '向量容器'
Vector_container vc {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};

LIVE with ctor taking initializer_list as parameter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2021-11-27
    • 2015-04-24
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多