【问题标题】:Constructor Calls For Class inheriting from vector Confusion构造函数调用类继承自向量混淆
【发布时间】:2021-11-06 15:30:28
【问题描述】:

在下面的代码中,我创建了一个继承自标准向量类的向量类。我很困惑为什么在 main 中,当我包含以下行时,我的 Vector 对象不调用派生类构造函数

using vector<T>::vector;

但是当我不包含它时,它会按预期调用我的派生类构造函数。这是什么原因?我无法用玩具代码复制问题,因此非常感谢。

#include <iostream>
#include <vector>
using namespace std;

template <class T>
class Vector : public vector<T>
{   
    vector <T> x;
    //using vector<T>::vector;
    public:
    Vector(vector <T> x)
    {
        this->x = x;
        for (auto i: this->x)
            cout << i << " ";
    }
    
};

int main() {
    Vector <int> x({1,2,3,4,5});
    return 0;
}

【问题讨论】:

  • Re:“从标准向量类继承”——这通常是个坏主意。 std::vector 并非旨在用作基类。

标签: c++ inheritance vector constructor


【解决方案1】:

您将{1,2,3,4,5}(不是std::vector)作为参数传递给Vector。由于std::vector 为该类型提供了a better match,并且您要求重用其构造函数,因此直接构造它。

如果您改为传递std::vector&lt;int&gt;{1,2,3,4,5},则为your constructor gets called

另请注意,您的示例代码将 2 std::vectors 构造为 Vector(继承的一个和成员 x)和 using namespace std is considered bad practice 的一部分。

【讨论】:

    猜你喜欢
    • 2017-03-18
    • 2020-01-12
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    相关资源
    最近更新 更多