[英]Call a virtual function inside the constructor using an object-expression
[英]Using object inside constructor
我正在創建自己的繼承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::
容器的形式,它們沒有虛擬的析構函數,如果從指向基礎的指針中刪除,它們會炸毀您的臉。
編輯如果需要在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中定義的算法(累加等)不同,而不是專注於矢量類和添加成員函數,則可以考慮為期望特定矢量的矢量編寫通用算法。代替。 然后,您根本不必考慮繼承,並且通用算法可以在向量的不同概念上工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.