首先,你發佈,因爲這行不能編譯代碼:
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中定義的算法不同的向量(積累,等等),而不是專注於向量類和添加成員函數,您可以考慮爲期望具體向量概念的向量編寫泛型算法。那麼你根本不必考慮繼承,而且你的泛型算法可以處理不同的矢量概念。
IIRC你甚至不應該從stl容器繼承。最好在矢量上打包,而不是繼承它。 – dtech