在构造函数中使用对象

Using object inside constructor

本文关键字:对象 构造函数      更新时间:2023-10-16

我正在创建继承STL的自己的向量类。我在创建对象时遇到了一个问题。

这是我的班。

using namespace std;
template <class T> 
class ArithmeticVector : public vector<T>{
public:
    vector<T> vector; //maybe I should not initalize this
    ArithmeticVector(){};
    ArithmeticVector(T n) : vector(n){
   //something here
};
在主要

;

ArithmeticVector<double> v9(5);

ArithmeticVector<int> v1(3);

我想要的是创建v9矢量或v1矢量就像STL矢量类型。但我得到的是新创建对象中的一个向量。首先,我想让我的对象是一个向量。

也许我应该在构造函数中使用v1对象?谢谢你的帮助。

如果您需要在std::vector上进行元素操作和数学运算,请使用std::valarray。如果没有,我不明白你为什么要子类化std::vector

不要继承std::容器,它们没有虚析构函数,如果从指向基的指针中删除,会在你脸上爆炸。

EDIT如果需要在std::vector上定义操作,可以在类外定义操作符,并使用其公共接口。

首先,您发布的代码无法编译,因为这一行:

public:
    vector<T> vector; //maybe i should not initalize this

你应该看到这个错误:

 declaration of ‘std::vector<T, std::allocator<_Tp1> > ArithmeticVector<T>::vector’
/usr/include/c++/4.4/bits/stl_vector.h:171: error: changes meaning of ‘vector’ from ‘class std::vector<T, std::allocator<_Tp1> >’

,因为你在类模板声明之上引入了整个STD命名空间,使得名称"vector"可见,然后你用它来声明一个对象。这就像写"double double;"。

我想要的是创建v9矢量或v1矢量就像STL矢量类型。

如果这是你想要的,下面是完成它的代码:

#include <vector>
#include <memory>
template
<
    class Type
>
class ArithmeticVector
:
    public std::vector<Type, std::allocator<Type> >
{
    public: 
        ArithmeticVector()
        :
            std::vector<Type>()
        {}
        // Your constructor takes Type for an argument here, which is wrong: 
        // any type T that is not convertible to std::vector<Type>::size_type
        // will fail at this point in your code; ArithmeticVector (T n)
        ArithmeticVector(typename std::vector<Type>::size_type t)
            :
                std::vector<Type>(t)
        {}
        template<typename Iterator>
        ArithmeticVector(Iterator begin, Iterator end)
        :
            std::vector<Type>(begin, end)
        {}
};
int main(int argc, const char *argv[])
{
    ArithmeticVector<double> aVec (3);  
    return 0;
}

如果你对与STL中定义的算法(累加等)不同的向量的算术运算感兴趣,而不是专注于向量类和添加成员函数,你可以考虑为期望特定向量概念的向量编写泛型算法。这样你就完全不用考虑继承问题了,你的泛型算法可以在不同的vector概念上工作。