2013-05-19 206 views
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 
}; 

In main;我打電話給這個;

ArithmeticVector<double> v9(5); 

ArithmeticVector<int> v1(3); 

我想創造v9載體或v1載體就像STL向量類型是什麼。但是我得到的是我新創建的對象中的一個矢量。我首先想讓自己的對象成爲一個向量。

也許我應該在構造函數中使用v1對象?感謝幫助。

+1

IIRC你甚至不應該從stl容器繼承。最好在矢量上打包,而不是繼承它。 – dtech

回答

4

如果您需要std::vector的元素操作和數學運算,請使用std::valarray。如果沒有,我不明白你爲什麼繼承std::vector

不要繼承表單std::容器,它們沒有虛擬析構函數,並且如果從基指針中刪除,就會炸燬你的臉。

編輯如果您需要定義std::vector上的操作,您可以通過在類之外定義運算符並使用其公共接口。

+0

我想要的是這樣的:我想讓那些v1和v9成爲像vector的矢量 foo; foo(5);'但是在我的實現中,我在無用的v1 v9對象中獲得了一個法線向量。我需要將v1和v9視爲一個向量,而不是一個向量容器。 – erenkabakci

+0

@Akeara:你想在這個班上做什麼? – rubenvb

+0

我想定義新的函數來處理我的向量,如添加或分割兩個向量。但要做到這一點,我需要繼承向量類。但正如我所說每當我打電話給這些構造函數,我沒有得到一個v1向量或v9向量。我需要創建那些v1和v9作爲向量。 – erenkabakci

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名字空間類模板聲明使名稱「vector」可見,然後用它來聲明一個對象。這就像寫了「雙倍的雙倍」。

What i want is creating v9 vector or v1 vector just like STL vector type.

如果這是你想要的,這裏要說的是做它的代碼:

#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中定義的算法不同的向量(積累,等等),而不是專注於向量類和添加成員函數,您可以考慮爲期望具體向量概念的向量編寫泛型算法。那麼你根本不必考慮繼承,而且你的泛型算法可以處理不同的矢量概念。

相關問題