【问题标题】:How to inherit from STL containers properly? C++如何正确继承 STL 容器? C++
【发布时间】:2022-01-03 13:05:42
【问题描述】:

考虑这段代码:

struct MY_VECTOR : public vector<vector<int>> 
{
    int n = this->size();
    int m = (*this)[0].size(); //<== fixed   this[0].size()
    int at(int i, int j)
    {
        if (i < 0 || j < 0 || i >= n || j >= m)
            return 0;
        else
            return (*this)[i][j];
    }
};

我想访问元素但不抛出任何异常。 (我本可以进行operator[] 重载,但现在对我来说并不重要。)首先,我从未尝试过从 STL 容器继承,所以我什至不确定是否可以这样做。 (我已经读过这通常是一个坏主意,但至少我想试一试)。其次,我什至不确定一切是否会正常工作,因为正如我已经说过的那样,我从未尝试过这样做。所以我尝试创建MY_VECTOR 对象并调用它的构造函数。

struct MY_VECTOR : public vector<vector<int>>
{
    int n = this->size();
    int m = (*this)[0].size();
    int at(int i, int j)
    {
        if (i < 0 || j < 0 || i >= n || j >= m)
            return 0;
        else
            return (*this)[i][j];
    }
};

int main()
{
    int n;
    cin >> n;
    MY_VECTOR a(n, vector<int>(n));
}

它不能编译,我不明白为什么。 vector&lt;vector&lt;int&gt;&gt; 构造函数不是必须继承吗?还是有不同的问题,我没有看到?

编译器错误:“错误 E0289:没有构造函数实例“MY_VECTOR::MY_VECTOR”与参数列表匹配”

【问题讨论】:

标签: c++ oop inheritance constructor


【解决方案1】:

我认为你想要的不是从 STL 继承,而是创建一个具有 vector 成员变量的新类。就像其中一位 cmets 所说,从 STL 容器继承是不可取的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 2010-11-17
    • 2011-05-03
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多