从 Vector 继承构造函数

inherit constructors from vector

提问人:jmgrc 提问时间:3/30/2015 最后编辑:Filip Roséen - refpjmgrc 更新时间:3/30/2015 访问量:829

问:

在Stroustrup,C++编程语言第4版中,他在第79页编写了以下代码:

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <allocators>
using std::vector;
using namespace std;
template<class T>
class Vector : vector<T> 
{
private:
    T elem[50];
    int size;
public:
    ***using vector<T>::vector; // inherit constructors***
    T& operator[](size_type i) { check(i); return this−>elem(i); }
    const T& operator=(size_type i) const {
        check(i); 
        return this−>elem(i);
    }
    void check(size_type i) { if (this−>size()<i) throw Bad_index(i); }
};

int _tmain(int argc, _TCHAR* argv[])
{
    Vector <int> V{ 1, 2, 3, 4 };
    return 0;
}

当我编译程序时,我收到以下错误:

错误 3 错误 C2440:“正在初始化”:无法从 'initializer-list' 到 'Vector' c:\computer programming\c++ 编程 语言\代码\ch3\consoleapplication3\consoleapplication3\consoleapplication3.cpp 28 1 ConsoleApplication3

错误 1 错误 C2886:“vector>”:符号不能 在成员 using-declaration 中使用 C:\Computer Programming\C++ 编程 语言\代码\ch3\consoleapplication3\consoleapplication3\consoleapplication3.cpp 17 1 控制台应用程序3

错误 2 错误 C2886:“vector>”:符号不能 在成员 using-declaration 中使用 C:\Computer Programming\C++ 编程 语言\代码\ch3\consoleapplication3\consoleapplication3\consoleapplication3.cpp 17 1 控制台应用程序3 4 IntelliSense:没有构造函数“Vector::Vector [with T=int]“ 匹配参数列表 参数类型为:(int, int, int, int) c:\计算机编程\C++ 编程 语言\代码\Ch3\控制台应用程序3\控制台应用程序3\控制台应用程序3.cpp 28 16 控制台应用程序3

我的问题主要涉及错误 2 错误 C2886:它指的是 using 指令。Visual Basic 对错误的定义如下:

'class::identifier' : 符号不能在成员 using-declaration 中使用 using 声明使用符号,例如命名空间名称。using 声明用于声明基类成员。

斯特鲁斯特鲁普显然使用了它,但我未能复制他的方法。我缺少标题还是什么?有人可以解释我的错误吗?谢谢JMG。

C++ 矢量 构造函数 using-directives

评论

0赞 Neil Kirk 3/30/2015
我总是听说从 std 容器继承是个坏主意。看到斯特鲁斯特鲁普这样做,我感到非常惊讶。另外,如果您要声明自己的存储,我也看不出它的意义。为什么要从 vector 继承?
0赞 juanchopanza 3/30/2015
@NeilKirk 当人们这么说时,他们通常指的是公共继承,他们通常认为派生对象将从 poiter 中删除到 vector。在这种情况下,我不认为这是一个坏主意。
1赞 songyuanyao 3/30/2015
它适用于 clanggcc,但不适用于 vc
1赞 juanchopanza 3/30/2015
此 MCVE 有效。很可能是您的编译器不支持 C++11。
1赞 Galik 3/30/2015
在我的 Straustrup 书中,这是在第 97 页,而不是第 79 页,它与你在这里的代码不同。您正在继承并实现自己的内部数组,这似乎是多余的。std::vector

答: 暂无答案