2

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);

私が欲しいのは、STLベクター型と同じようにv9ベクターまたはベクターを作成することです。v1しかし、私が得たのは、新しく作成したオブジェクト内のベクトルです。最初はオブジェクトをベクトルにしたい。

v1コンストラクター内でそのオブジェクトを使用する必要がありますか?手伝ってくれてありがとう。

4

2 に答える 2

4

要素ごとの演算と a の計算が必要な場合はstd::vector、 を使用しますstd::valarray。そうでない場合は、サブクラス化する理由がわかりませんstd::vector

フォーム コンテナーを継承しないでくださいstd::。コンテナーには仮想デストラクタがなく、ポインターからベースへのポインターから削除されると、顔が爆発します。

編集で操作を定義する必要がある場合std::vectorは、クラスの外部で演算子を定義し、そのパブリック インターフェイスを使用して実行できます。

于 2013-05-19T15:15:19.283 に答える
1

まず、投稿したコードは、次の行のためにコンパイルできません。

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 名前空間全体を導入し、それを使用してオブジェクトを宣言するためです。それは「double double;」と書くようなものです。

私が欲しいのは、STLベクター型と同じようにv9ベクターまたはv1ベクターを作成することです。

これが必要な場合は、次のコードを実行します。

#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 で定義されているアルゴリズム (accumulate など) とは異なるベクトルの算術演算に関心がある場合は、ベクトル クラスに集中してメンバー関数を追加するのではなく、特定のベクトルの概念を期待するベクトルの汎用アルゴリズムを作成することを検討できます。代わります。そうすれば、継承についてまったく考える必要がなくなり、一般的なアルゴリズムはベクトルのさまざまな概念で機能します。

于 2013-05-19T15:31:48.583 に答える